1

我正在使用json-c 库,在查看文档后,我找不到不使用一堆循环来获得深度嵌套的键/值的方法,这就是我尝试过的:

json_object_object_foreach(json_data_obj, key, val) {
  printf("KEY:%s\t VAL:%s\n", key, json_object_to_json_string(val));
  /* TODO: Traverse the JSON
   * "results" => "channel" => "item" => "condition" => "temp"
   */
}

这是输出:

KEY:query        VAL:{ "count": 1, "created": "2015-04-10T06:05:12Z", "lang": "en-US", "results": { "channel": { "item": { "condition": { "code": "33", "date": "Thu, 09 Apr 2015 9:55 pm PDT", "temp": "56", "text": "Fair" } } } } }

如何在不多次使用 json_object_object_foreach() 宏的情况下获取临时值?

4

2 回答 2

2

同时(从 json-c 0.13 开始)可以通过使用json_c_visit函数遍历对象树来到达深度嵌套的对象。

int json_c_visit (
    json_object * jso,
    int future_flags,
    json_c_visit_userfunc * userfunc,
    void * userarg 
)   

该函数遍历 json 文档的每个对象并调用用户定义的函数userfunc。还可以使用 userfunc 的返回值来引导遍历树。以单元测试预期输出为例如何使用该功能。

于 2021-03-04T18:48:50.037 回答
1

您可能必须为每个对象调用 json_object_object_get_ex 直到获得所需的键/值对,并在此过程中检查每个键是否存在。

可能还有另一种方法,但这是我最近在处理同样复杂的 JSON 数据的项目中必须做的事情。

以下代码假定 b 包含您的 JSON 字符串。

json_object *json_obj, *results_obj, *channel_obj, *item_obj, *condition_obj,*temp_obj;
int exists;
char *temperature_string;

json_obj = json_tokener_parse(b); 
exists=json_object_object_get_ex(json_obj,"results",&results_obj);
if(exists==false) { 
  printf("\"results\" not found in JSON"); 
  return; 
} 
exists=json_object_object_get_ex(results_obj,"channel",&channel_obj); 
if(exists==false) { 
  printf("key \"channel\" not found in JSON"); 
  return; 
} 
exists=json_object_object_get_ex(channel_obj,"item",&item_obj); 
if(exists==false) { 
  printf("key \"item\" not found in JSON"); 
  return; 
}
exists=json_object_object_get_ex(item_obj,"condition",&condition_obj); 
if(exists==false) { 
  printf("key \"condition\" not found in JSON"); 
  return; 
}
exists=json_object_object_get_ex(condition_obj,"temp",&temp_obj); 
if(exists==false) { 
   printf("key \"temp\" not found in JSON"); 
   return; 
}
temperature_string = json_object_get_string(temp_obj); //temperature_string now contains "56"
于 2015-04-18T21:28:18.670 回答