如何使用json-c库循环遍历C中的键和值?

lsmd5eda  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(109)

我使用json-c来解析json。是否可以循环遍历键和值。json_object_object_get_ex():这个函数需要预先知道键是什么。如果我们不知道键,我们必须循环遍历它们怎么办?

whhtz7ly

whhtz7ly1#

您可以从json_object_object_foreach宏开始

#define json_object_object_foreach(obj, key, val)
char * key;
struct json_object * val;
for (struct lh_entry * entry = json_object_get_object(obj) -> head;
  ({
    if (entry) {
      key = (char * ) entry -> k;
      val = (struct json_object * ) entry -> v;
    };entry;
  }); entry = entry -> next)

字符串
对于用法,这个article有一个很好的例子。

#include <json/json.h>

#include <stdio.h>

int main() {
  char * string = "{"
  sitename " : "
  joys of programming ",
  "tags": ["c", "c++", "java", "PHP"],
  "author-details": {
    "name": "Joys of Programming",
    "Number of Posts": 10
  }
}
";
json_object * jobj = json_tokener_parse(string);
enum json_type type;
json_object_object_foreach(jobj, key, val) {
  printf("type: ", type);
  type = json_object_get_type(val);
  switch (type) {
  case json_type_null:
    printf("json_type_null\n");
    break;
  case json_type_boolean:
    printf("json_type_boolean\n");
    break;
  case json_type_double:
    printf("json_type_double\n");
    break;
  case json_type_int:
    printf("json_type_int\n");
    break;
  case json_type_object:
    printf("json_type_object\n");
    break;
  case json_type_array:
    printf("json_type_array\n");
    break;
  case json_type_string:
    printf("json_type_string\n");
    break;
  }
}
}

相关问题