在Linux环境下,使用C语言解析JSON数据通常需要借助第三方库,cJSON、Jansson 等,这里以 cJSON 为例,介绍如何在 Linux 下使用 C 语言解析 JSON 数据。
确保已经安装了 cJSON 库,在终端中执行以下命令安装:

(图片来源网络,侵删)
sudo apt-get install libjson-c-dev
我们通过一个简单的示例来展示如何使用 cJSON 库解析 JSON 数据。
示例 :解析以下 JSON 数据:
{
"name": "张三",
"age": 30,
"is_student": false,
"scores": {
"math": 90,
"english": 85
},
"hobbies": ["reading", "swimming"]
} 创建一个名为json_parse.c 的文件,编写以下代码:
#include <stdio.h>
#include <json-c/json.h>
void print_value(json_object *jobj, const char *key) {
const char *value = json_object_get_string(json_object_object_get(jobj, key));
if (value) {
printf("%s: %s
", key, value);
} else {
int int_value = json_object_get_int(json_object_object_get(jobj, key));
printf("%s: %d
", key, int_value);
}
}
void print_object(json_object *jobj) {
const char *key;
json_object_object_foreach(jobj, key, print_value);
}
void print_array(json_object *jobj, const char *key) {
json_object *jarray = json_object_object_get(jobj, key);
int n = json_object_array_length(jarray);
for (int i = 0; i < n; i++) {
const char *value = json_object_get_string(json_object_array_get_idx(jarray, i));
printf("%s[%d]: %s
", key, i, value);
}
}
int main() {
const char *json_str = "{
"
" "name": "张三",
"
" "age": 30,
"
" "is_student": false,
"
" "scores": {
"
" "math": 90,
"
" "english": 85
"
" },
"
" "hobbies": ["reading", "swimming"]
"
"}";
json_object *jobj = json_tokener_parse(json_str);
print_object(jobj);
printf("Scores:
");
json_object *scores = json_object_object_get(jobj, "scores");
print_object(scores);
printf("Hobbies:
");
print_array(jobj, "hobbies");
json_object_put(jobj);
return 0;
} 编译并运行程序:
gcc json_parse.c -o json_parse -ljson-c ./json_parse
输出结果如下:

(图片来源网络,侵删)
age: 30 hobbies: reading, swimming is_student: 0 name: 张三 Scores: english: 85 math: 90 Hobbies: hobbies[0]: reading hobbies[1]: swimming
示例展示了如何使用 cJSON 库在 Linux 下用 C 语言解析 JSON 数据,根据实际需求,可以对示例代码进行相应的修改和扩展。

(图片来源网络,侵删)
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/55086.html