4

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
selvam
  • 59
  • 1
  • 5
  • 2
    What have you tried so far? What problems do you have with your code? How does, or doesn't it work? Can you please try to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us? And if you haven't done so yeyt, please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). – Some programmer dude Jan 19 '16 at 12:20
  • @Jochimpileborg :Thanks for your comment.Will post clear questions next time. – selvam Jan 29 '16 at 06:45

2 Answers2

12

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;
   }
}
Ilya
  • 5,377
  • 2
  • 18
  • 33
  • 1
    Thanks a lot it worked. In while loop i printed key using printf("Key is %s",device->string); – selvam Jan 29 '16 at 07:01
1

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.

Jonatan
  • 3,752
  • 4
  • 36
  • 47
  • 6
    About the implementation detail: I try to not break API and ABI, this means that this will work for 1.x.x versions indefinitely without `cJSON_ArrayForEach`. The cJSON struct in v2 will change for sure, but `next` and `child` will probably stay the same. (I'm the maintainer of cJSON). – FSMaxB Feb 02 '18 at 16:46