我使用json-c解析以下JSON字符串:
{
"root": {
"a": "1",
"b": "2",
"c": "3"
}
}还有,我有以下C代码。上面的JSON存储在变量b中。
json_object *new_obj, *obj1, *obj2;
int exists;
new_obj = json_tokener_parse(b);
exists=json_object_object_get_ex(new_obj,"a",&obj1);
if(exists==false) {
printf("key \"a\" not found in JSON");
return;
}
exists=json_object_object_get_ex(new_obj,"b",&obj2);
if(exists==false) {
printf("key \"b\" not found in JSON");
return;
}从使用json_object_get_ex的"a“键中获取值的正确键名是什么?
对于上面的JSON,我没有工作(这两个查询都是假的),但是对于下面的JSON确实有效。我确信这与对“路径”到"a“使用哪一个键的误解有关。
{
"a": "1",
"b": "2",
"c": "3"
}发布于 2015-04-18 20:59:14
好的,我知道了,就像我说的,我误解了json-c是如何解析原始JSON文本并将其表示为父节点和子节点的。
下面的代码正在工作。问题是,我试图从原始的json_object中获取子节点,这是不正确的。我首先必须获得根对象,然后从根获取子对象。
json_object *new_obj, *root_obj, *obj1, *obj2;
int exists;
new_obj = json_tokener_parse(b);
exists=json_object_object_get_ex(new_obj,"root",&root_obj);
if(exists==false) {
printf("\"root\" not found in JSON");
return;
}
exists=json_object_object_get_ex(root_obj,"a",&obj1);
if(exists==false) {
printf("key \"a\" not found in JSON");
return;
}
exists=json_object_object_get_ex(root_obj,"b",&obj2);
if(exists==false) {
printf("key \"b\" not found in JSON");
return;
}https://stackoverflow.com/questions/29710971
复制相似问题