如何以通用方式在cJSON中解析以下对象

问题描述 投票:-1回答:1

由于我是cJOSN解析器的新手,请有人以通用方式帮助解析以下json。

这里名称强度是固定的。因此,如果我选择person1,则必须获取person1的名称和强度键值。(人数可能会增加或减少)

{
  "details": [
    {
      "person1": [
        {
          "name": "xxx",
          "strength": "abc"
        }
      ],
      "person2": [
        {
          "name": "yyy",
          "strength": "def"

        }
      ],
      "person3": [
        {
          "name": "zzz",
          "strength": "abc"

        }
      ]
    }
  ]
}
c cjson
1个回答
0
投票

documentation似乎是一个不错的起点。这是一个可复制的答案:

#include <stdio.h>
#include "cJSON.h"

const char *myJsonString = "{" \
"  \"details\": [ " \
"    { " \
"      \"person1\": [ " \
"        { " \
"          \"name\": \"xxx\", " \
"          \"strength\": \"abc\" " \
"        } " \
"      ], " \
"      \"person2\": [ " \
"        { " \
"          \"name\": \"yyy\", " \
"          \"strength\": \"def\" " \
"        } " \
"      ], " \
"      \"person3\": [ " \
"        { " \
"          \"name\": \"zzz\", " \
"          \"strength\": \"abc\" " \
"        } " \
"      ] " \
"    } " \
"  ] " \
"}";

int main()
{
    cJSON *root = cJSON_Parse(myJsonString);
    cJSON *details = cJSON_GetObjectItem(root, "details");
    int detailsIndex;
    for (detailsIndex = 0; detailsIndex < cJSON_GetArraySize(details); detailsIndex++) {
        cJSON *people = cJSON_GetArrayItem(details, detailsIndex);
        int personIndex;
        for (personIndex = 0; personIndex < cJSON_GetArraySize(people); personIndex++) {
            cJSON *personItems = cJSON_GetArrayItem(people, personIndex);
            const char *personKeyName = personItems->string;
            int itemIndex;
            for (itemIndex = 0; itemIndex < cJSON_GetArraySize(personItems); itemIndex++) {
                cJSON *personItem = cJSON_GetArrayItem(personItems, itemIndex);
                const char *name =  cJSON_GetObjectItem(personItem, "name")->valuestring;
                const char *strength = cJSON_GetObjectItem(personItem, "strength")->valuestring;
                fprintf(stderr, "personKeyName [%s] name [%s] strength [%s]\n", personKeyName, name, strength);
            }
        }
    }
    cJSON_Delete(root);
    return 0;
}

要编译:

$ wget -qO- https://raw.githubusercontent.com/insertion/cJOSN/master/cJSON.c > cJSON.c
$ wget -qO- https://raw.githubusercontent.com/insertion/cJOSN/master/cJSON.h > cJSON.h
$ gcc -Wall cJSON.c test.c -o test -lm

要运行:

$ ./test
personKeyName [person1] name [xxx] strength [abc]
personKeyName [person2] name [yyy] strength [def]
personKeyName [person3] name [zzz] strength [abc]
© www.soinside.com 2019 - 2024. All rights reserved.