在 c 中迭代一个 cJSON 嵌套对象

iterate an cJSON nested object in c

如何迭代嵌套的cJSON对象?我想从 C 中的 deviceData 父对象获取(打印)所有键和值。它是一个 cJson 对象。

 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"
                    }
           }
    };

如何在 C 中打印 deviceData(ex device0 device1 device 2 等)的密钥。提前致谢。

假设 obj 是一个包含你的对象的字符串,你解析它然后使用 next 迭代:

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;
   }
}

cJSON 文档中有一条关于遍历对象的评论:

To iterate over an object, you can use the cJSON_ArrayForEach macro the same way as for arrays.

参见:https://github.com/DaveGamble/cJSON#objects

cJSON_ArrayForEach 宏基本上与 ilya 的提议相同,但它避免了依赖 cJSON 实现细节。