How to iterate nested cJSON object? i want to get(print) all keys and values from deviceData parent object in C. Its a cJson object.
obj = { "command": "REPLACE_ROWS",
"table": "Device.XXX",
"deviceData": {
"device0": {
"DeviceName": "Filtered Device",
"MACAddress": "112233445599"
},
"device1": {
"DeviceName": "Filtered Device",
"MACAddress": "112233445599"
},
"device2": {
"DeviceName": "Filtered Device",
"MACAddress": "112233445599"
}
}
};
how to print keys of deviceData (ex device0 device1 device 2 and so on) in C. Thanks in advance.
Supposing obj
is a string containing your object, you parse it then use next
to iterate:
cJSON * root = cJSON_Parse(obj);
cJSON * deviceData = cJSON_GetObjectItem(root,"deviceData");
if( deviceData ) {
cJSON *device = deviceData->child;
while( device ) {
// get and print key
device = device->next;
}
}
There's a comment in the cJSON documentation about iterating over an object:
To iterate over an object, you can use the cJSON_ArrayForEach macro the same way as for arrays.
See: https://github.com/DaveGamble/cJSON#objects
The cJSON_ArrayForEach
macro basically does the same as ilya's proposal, but it avoids relying on cJSON implementation details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With