PureBasic
PureBasic
JSON: Array of Objects
See more JSON Examples
Here we have a JSON object that contains an array, where each element in the array is a JSON object. This example demonstrates how to access the objects contained within an array.
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
}
Chilkat PureBasic Downloads
IncludeFile "CkJsonArray.pb"
IncludeFile "CkJsonObject.pb"
Procedure ChilkatExample()
success.i = 0
json.i = CkJsonObject::ckCreate()
If json.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
; This is the above JSON with whitespace chars removed (SPACE, TAB, CR, and LF chars).
; The presence of whitespace chars for pretty-printing makes no difference to the Load
; method.
jsonStr.s = "{" + Chr(34) + "employees" + Chr(34) + ":[{" + Chr(34) + "firstName" + Chr(34) + ":" + Chr(34) + "John" + Chr(34) + ", " + Chr(34) + "lastName" + Chr(34) + ":" + Chr(34) + "Doe" + Chr(34) + "},{" + Chr(34) + "firstName" + Chr(34) + ":" + Chr(34) + "Anna" + Chr(34) + ", " + Chr(34) + "lastName" + Chr(34) + ":" + Chr(34) + "Smith" + Chr(34) + "},{" + Chr(34) + "firstName" + Chr(34) + ":" + Chr(34) + "Peter" + Chr(34) + "," + Chr(34) + "lastName" + Chr(34) + ":" + Chr(34) + "Jones" + Chr(34) + "}]}"
success = CkJsonObject::ckLoad(json,jsonStr)
If success <> 1
Debug CkJsonObject::ckLastErrorText(json)
CkJsonObject::ckDispose(json)
ProcedureReturn
EndIf
; Get the "employees" array.
employees.i = CkJsonObject::ckArrayOf(json,"employees")
If CkJsonObject::ckLastMethodSuccess(json) = 0
Debug "employees member not found."
CkJsonObject::ckDispose(json)
ProcedureReturn
EndIf
; Iterate over each employee, getting the JSON object at each index.
numEmployees.i = CkJsonArray::ckSize(employees)
i.i = 0
While i < numEmployees
empObj.i = CkJsonArray::ckObjectAt(employees,i)
Debug "employee[" + Str(i) + "] = " + CkJsonObject::ckStringOf(empObj,"firstName") + " " + CkJsonObject::ckStringOf(empObj,"lastName")
CkJsonObject::ckDispose(empObj)
i = i + 1
Wend
CkJsonArray::ckDispose(employees)
CkJsonObject::ckDispose(json)
ProcedureReturn
EndProcedure