0

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

这里名称力量是固定的。所以如果我选择person1,必须得到person1的名字和强度键值。(人数可能增加或减少)

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

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

        }
      ]
    }
  ]
}
4

1 回答 1

0

文档似乎是一个很好的起点。这是一个最低限度可重复的答案:

#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]
于 2020-04-30T08:55:58.007 回答