我正在使用 json-c 库。尝试在 C 中解析 json 文件时遇到两个问题。
如果我尝试按原样解析文件,则会在json_object_object_foreach()
.
但是,如果我删除了 json 文件开头和结尾的方括号,它可以工作,但只解析第一个对象。我想解析整个 json 文件。
这是我的代码:
int ParseJson(const char *file)
{
char *json;
int fd;
struct json_object *obj;
struct stat st;
fd = open(file, O_RDONLY);
json = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
close(fd);
obj = json_tokener_parse(json);
json_object_object_foreach(obj, key, val) {
printf("key = %s value = %s\n",key, json_object_get_string(val));
}
return 0;
}
这是我的 json 文件:
[{
"test_1": "min",
"test_2": "max",
"test_3": "val",
"test_4": "res",
"test_5": "var",
"test_6": "hal"
}, {
"fetch_1": 300.00,
"fetch_2": 100.000,
"fetch_3": 0.000000,
"fetch_4": 0.000000,
"fetch_5": 20.00
}, {
"fetch_1": 250.00,
"fetch_2": 310.000,
"fetch_3": 3.000000,
"fetch_4": 7.000000,
"fetch_5": 18.00
}, {
"fetch_1": 450.00,
"fetch_2": 678.000,
"fetch_3": 3.000000,
"fetch_4": 3.000000,
"fetch_5": 89.00
}, {
"fetch_1": 300.00,
"fetch_2": 100.000,
"fetch_3": 7.000000,
"fetch_4": 67.000000,
"fetch_5": 50.00
}, {
"fetch_1": 900.00,
"fetch_2": 800.000,
"fetch_3": 6.000000,
"fetch_4": 5.000000,
"fetch_5": 30.00
}]