C
C
Loading and Parsing a JSON Array
See more JSON Examples
A JSON array is JSON that begins with "[" and ends with "]". For example, this is a JSON array that contains 3 JSON objects.
[{"name":"jack"},{"name":"john"},{"name":"joe"}]
A JSON object, however, is JSON that begins with "{" and ends with "}". For example, this JSON is an object that contains an array.
{"pets":[{"name":"jack"},{"name":"john"},{"name":"joe"}]}
This example shows how loading a JSON array is different than loading a JSON object.
Chilkat C Downloads
#include <C_CkJsonArray.h>
#include <C_CkJsonObject.h>
void ChilkatSample(void)
{
const char *strJsonArray;
const char *strJsonObject;
HCkJsonArray jsonArray;
int i;
HCkJsonObject jsonObj;
HCkJsonObject jsonObject;
int numPets;
strJsonArray = "[{\"name\":\"jack\"},{\"name\":\"john\"},{\"name\":\"joe\"}]";
strJsonObject = "{\"pets\":[{\"name\":\"jack\"},{\"name\":\"john\"},{\"name\":\"joe\"}]}";
// A JSON array must be loaded using JsonArray:
jsonArray = CkJsonArray_Create();
CkJsonArray_Load(jsonArray,strJsonArray);
// Examine the values:
i = 0;
while (i < CkJsonArray_getSize(jsonArray)) {
jsonObj = CkJsonArray_ObjectAt(jsonArray,i);
printf("%d: %s\n",i,CkJsonObject_stringOf(jsonObj,"name"));
CkJsonObject_Dispose(jsonObj);
i = i + 1;
}
// Output is:
// 0: jack
// 1: john
// 2: joe
// A JSON object must be loaded using JsonObject
jsonObject = CkJsonObject_Create();
CkJsonObject_Load(jsonObject,strJsonObject);
// Examine the values:
i = 0;
numPets = CkJsonObject_SizeOfArray(jsonObject,"pets");
while (i < numPets) {
CkJsonObject_putI(jsonObject,i);
printf("%d: %s\n",i,CkJsonObject_stringOf(jsonObject,"pets[i].name"));
i = i + 1;
}
// Output is:
// 0: jack
// 1: john
// 2: joe
CkJsonArray_Dispose(jsonArray);
CkJsonObject_Dispose(jsonObject);
}