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



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

可以从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)

对于用法,本文有一个很好的例子。

#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_nulln");
break;
case json_type_boolean:
printf("json_type_booleann");
break;
case json_type_double:
printf("json_type_doublen");
break;
case json_type_int:
printf("json_type_intn");
break;
case json_type_object:
printf("json_type_objectn");
break;
case json_type_array:
printf("json_type_arrayn");
break;
case json_type_string:
printf("json_type_stringn");
break;
}
}
}

相关内容

  • 没有找到相关文章

最新更新