使用cJSON读取密钥

时间:2019-12-06 04:49:03

标签: c cjson

我正在使用cJSON解析包含键值的字符串。我想动态生成我的结构,为此,我需要从该字符串中读取所有键。

例如我有一个像下面的json,我想在运行时读取所有键。我不知道json中会出现所有的键。

{
    "name": "abc",
    "class": "First",
    "division": "A",
    "age": "10"
}

如何在不真正知道键的情况下读取键和值?

我尝试使用指针链接到下一个孩子,但这似乎并没有给我正确的值。

cJSON *root = cJSON_Parse(strMyJson);
cJSON *temp = root;

std::cout << "----------" << temp->child->string << "\n";//displays key - correct
std::cout << "----------" << temp->child->valuestring << "\n"; //displays value - correct

//below starts causing problem
temp = temp->child->next;

while (temp != NULL)
{
    std::cout << "----------" << temp->string << "\n";
    std::cout << "----------" << temp->valuestring << "\n";
    temp = temp->child->next;
}

感谢您的帮助!

-谢谢, S

2 个答案:

答案 0 :(得分:0)

已解决的问题 不知道为什么,但是我需要分别处理根本原因。

以下代码有效!

        cJSON *root = cJSON_Parse(strMyJson);
        if(NULL == root)
        {
            std::cout << __func__ << " invalid JSON\n";
            return false;
        }

        cJSON *temp = root;

        temp = temp->child->next;

        std::cout << "value: " << temp->valuestring << "\t";
        std::cout << "key : " << temp->string << "\n";

        temp = temp->next;

        while (temp != NULL)
        {

            std::cout << "----------" << temp->string << "\n";
            std::cout << "----------" << temp->valuestring << "\n";

            temp = temp->next;
        }

-谢谢, S

答案 1 :(得分:0)

根JSON的结构如下:

{ -----------------------------> root  : cJSON_Object 
    "name": "abc",-------------> child : cJSON_String
    "class": "First",----------> child->next : cJSON_String
    "division": "A",-----------> child->next->next : cJSON_String
    "age": "10"----------------> child->next->next->next : cJSON_String
}

简短摘要将帮助您了解cJSON的工作原理:)

int main(void)
{
  cJSON *root = cJSON_Parse(jsonstring);
  cJSON *temp = root;
  printf("root item's type--- %d\n", temp->type);      //root item's type is cJSON_Object


  printf("type--- %d\n", temp->child->type);      // cJSON type: 16 cJSON_String; 64 cJSON_Object
  printf("string--- %s\n", temp->child->string);      //displays key - correct
  printf("string--- %s\n", temp->child->valuestring);; //displays value - correct

  temp = temp->child->next;
  char *tempstr = cJSON_Print(temp);
  printf("tempstr = %s\n", tempstr);
  while (temp != NULL)
  {
    printf("type--- %d\n", temp->type);      //displays type - correct
    printf("string--- %s\n", temp->string);      //displays key - correct
    printf("string--- %s\n", temp->valuestring); //displays value - correct
    temp = temp->next;
  }
}