我使用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;
}感谢您的帮助!
-Thanks,S
发布于 2019-12-06 13:52:44
解决了问题不确定为什么,但我需要单独处理根情况。
下面的代码起作用了!
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;
}-Thanks,S
发布于 2020-04-01 17:03:53
根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
}blow snippet将帮助您理解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;
}
}https://stackoverflow.com/questions/59207045
复制相似问题