我正在使用 json-c 来解析 json。是否可以遍历键和值。json_object_object_get_ex() :这个函数需要事先知道键是什么。如果我们不知道密钥,我们必须遍历它们怎么办。
问问题
157 次
1 回答
0
您可以从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;
}
}
}
于 2021-09-17T06:52:37.570 回答