[英]How to find a name in a name/value pair using cJSON
cJSON provides a function cJSON 提供了一个函数
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
I created a test function我创建了一个测试函数
#include "cJSON.h"
const char *jsonstring = "{\"b\": {\"b1\":\"2b\"}}";
void jsontest(void)
{
cJSON *cJSON_data = cJSON_Parse(jsonstring);
char *buffer = cJSON_Print(cJSON_data);
printf("JSON_String:%s\r\n",buffer);
cJSON *bfound = cJSON_GetObjectItemCaseSensitive(cJSON_data,"b1");
printf("bfound: 0x%08x\n",(char*)bfound);
free(cJSON_data);
free(buffer);
}
The output is输出是
JSON_String:{
"b": {
"b1": "2b"
}
}
bfound: 0x00000000
` `
If I use this string,如果我使用这个字符串,
const char *jsonteststr1 = "{\\"a\\":\\"1\\",\\"b\\":\\"2\\",\\"c\\":\\"3\\"}";
GetObjectItemCaseSensitive()
will find "a", "b", and "c". GetObjectItemCaseSensitive()
将找到“a”、“b”和“c”。
GetObjectItemCaseSensitive()
does not seem to recurse. GetObjectItemCaseSensitive()
似乎没有递归。
Am I doing something wrong?难道我做错了什么? Do I not understand how to use
GetObjectItem()
?我不明白如何使用
GetObjectItem()
吗?
I am using version 1.7.12我使用的是 1.7.12 版
cJSON_GetObjectItemCaseSensitive(object, string)
can only get the the direct child and child's siblings of object
, we can't find the child's child node through it. cJSON_GetObjectItemCaseSensitive(object, string)
只能得到直接孩子和孩子的兄弟姐妹object
,我们无法通过它发现孩子的子节点。
if you want to get the value of 2b
, then you should:如果你想获得
2b
的值,那么你应该:
#include "cJSON.h"
const char *jsonstring = "{\"b\": {\"b1\":\"2b\"}}";
void jsontest(void)
{
cJSON *cJSON_data = cJSON_Parse(jsonstring);
char *buffer = cJSON_Print(cJSON_data);
printf("JSON_String:%s\r\n",buffer);
cJSON *bfound = cJSON_GetObjectItemCaseSensitive(cJSON_data,"b"); // cJSON_data only has a child which named "b"
cJSON *b1_found = cJSON_GetObjectItemCaseSensitive(bfound, "b1"); // key/value: <b1, 2b> is in b1_found, not bfound
printf("b1_found: 0x%08x\n",(char*)b1_found);
printf("bfound: 0x%08x\n",(char*)bfound);
cJSON_Delete(cJSON_data); // you should use cJSON_Delete to free the json item.
free(buffer);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.