PureBasic
PureBasic
JSON: Miscellaneous Operations
See more JSON Examples
Demonstrates a variety of JSON API methods. This example uses the following JSON document:
{
"alphabet": "abcdefghijklmnopqrstuvwxyz",
"sampleData" : {
"pi": 3.14,
"apple": "juicy",
"hungry": true,
"withoutValue": null,
"answer": 42
}
}
Chilkat PureBasic Downloads
IncludeFile "CkJsonObject.pb"
Procedure ChilkatExample()
success.i = 0
json.i = CkJsonObject::ckCreate()
If json.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkJsonObject::setCkEmitCompact(json, 0)
; Assume the file contains the data as shown above..
success = CkJsonObject::ckLoadFile(json,"qa_data/json/sample2.json")
If success = 0
Debug CkJsonObject::ckLastErrorText(json)
CkJsonObject::ckDispose(json)
ProcedureReturn
EndIf
; Get the "sampleData" object:
sampleData.i = CkJsonObject::ckCreate()
If sampleData.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkJsonObject::ckObjectOf2(json,"sampleData",sampleData)
; Demonstrate BoolAt and BoolOf
Debug "hungry: " + Str(CkJsonObject::ckBoolOf(sampleData,"hungry"))
Debug "hungry: " + Str(CkJsonObject::ckBoolAt(sampleData,2))
; StringOf returns the value as a string regardless of it's actual type:
Debug "pi: " + CkJsonObject::ckStringOf(sampleData,"pi")
Debug "answer: " + CkJsonObject::ckStringOf(sampleData,"answer")
Debug "withoutValue: " + CkJsonObject::ckStringOf(sampleData,"withoutValue")
Debug "hungry: " + CkJsonObject::ckStringOf(sampleData,"hungry")
; Demonstrate IsNullOf / IsNullAt
Debug "withoutValue is null? " + Str(CkJsonObject::ckIsNullOf(sampleData,"withoutValue"))
Debug "withoutValue is null? " + Str(CkJsonObject::ckIsNullAt(sampleData,3))
Debug "apple is null? " + Str(CkJsonObject::ckIsNullOf(sampleData,"apple"))
Debug "apple is null? " + Str(CkJsonObject::ckIsNullAt(sampleData,1))
; IntOf
Debug "answer: " + Str(CkJsonObject::ckIntOf(sampleData,"answer"))
; SetNullAt, SetNullOf
; Set "pi" to null
success = CkJsonObject::ckSetNullAt(sampleData,0)
; Set "answer" to null
success = CkJsonObject::ckSetNullOf(sampleData,"answer")
; Show the changes:
Debug CkJsonObject::ckEmit(json)
; Restore pi and apple:
success = CkJsonObject::ckSetNumberAt(sampleData,0,"3.14")
success = CkJsonObject::ckSetNumberOf(sampleData,"answer","42")
; Show the changes:
Debug CkJsonObject::ckEmit(json)
; Add a null value named "afterApple" just after "apple"
success = CkJsonObject::ckAddNullAt(sampleData,2,"afterApple")
; Add a boolean value just after "pi"
success = CkJsonObject::ckAddBoolAt(sampleData,1,"afterPi",0)
; Examine the changes..
Debug CkJsonObject::ckEmit(json)
CkJsonObject::ckDispose(json)
CkJsonObject::ckDispose(sampleData)
ProcedureReturn
EndProcedure