Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate an cJSON nested object in c

Tags:

c

cjson

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.

like image 563
selvam Avatar asked Sep 14 '25 18:09

selvam


2 Answers

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;
   }
}
like image 115
Ilya Avatar answered Sep 16 '25 08:09

Ilya


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.

like image 43
Jonatan Avatar answered Sep 16 '25 08:09

Jonatan