在Linux上使用C语言解析JSON数据,通常可以使用一些流行的库,如cJSON 和Jansson,这些库提供了方便的API来解析、生成和操作JSON数据,下面将详细介绍如何使用这两个库来解析JSON数据。
cJSON 库

(图片来源网络,侵删)
安装 cJSON
可以通过包管理器安装cJSON,在Debian/Ubuntu系统上可以使用以下命令:
sudo apt-get install libcjson-dev
示例代码
下面是一个简单的示例,演示如何使用cJSON库来解析JSON数据:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"
int main() {
// JSON字符串
const char *json_string = "{"name": "John", "age": 30, "city": "New York"}";
// 解析JSON字符串
cJSON *root = cJSON_Parse(json_string);
if (root == NULL) {
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
fprintf(stderr, "Error before: %s
", error_ptr);
}
return -1;
}
// 获取JSON对象中的值
cJSON *name = cJSON_GetObjectItemCaseSensitive(root, "name");
if (name != NULL && cJSON_IsString(name)) {
printf("Name: %s
", name->valuestring);
}
cJSON *age = cJSON_GetObjectItemCaseSensitive(root, "age");
if (age != NULL && cJSON_IsNumber(age)) {
printf("Age: %d
", age->valueint);
}
cJSON *city = cJSON_GetObjectItemCaseSensitive(root, "city");
if (city != NULL && cJSON_IsString(city)) {
printf("City: %s
", city->valuestring);
}
// 释放内存
cJSON_Delete(root);
return 0;
} 编译与运行

(图片来源网络,侵删)
假设文件名为main.c,可以使用以下命令编译并运行程序:
gcc main.c -o main -lcjson ./main
Jansson 库
安装 Jansson
可以通过包管理器安装Jansson,在Debian/Ubuntu系统上可以使用以下命令:
sudo apt-get install libjansson-dev
示例代码

(图片来源网络,侵删)
下面是一个简单的示例,演示如何使用Jansson库来解析JSON数据:
#include <stdio.h>
#include <stdlib.h>
#include <jansson.h>
int main() {
// JSON字符串
const char *json_string = "{"name": "John", "age": 30, "city": "New York"}";
// 解析JSON字符串
json_t *root;
json_error_t error;
root = json_loads(json_string, 0, &error);
if (!root) {
fprintf(stderr, "Error parsing JSON: %s
", error.text);
return -1;
}
// 获取JSON对象中的值
json_t *name = json_object_get(root, "name");
if (name != NULL && json_is_string(name)) {
printf("Name: %s
", json_string_value(name));
}
json_t *age = json_object_get(root, "age");
if (age != NULL && json_is_integer(age)) {
printf("Age: %d
", json_integer_value(age));
}
json_t *city = json_object_get(root, "city");
if (city != NULL && json_is_string(city)) {
printf("City: %s
", json_string_value(city));
}
// 释放内存
json_decref(root);
return 0;
} 编译与运行
假设文件名为main.c,可以使用以下命令编译并运行程序:
gcc main.c -o main -ljansson ./main
介绍了如何在Linux环境中使用C语言解析JSON数据的两种方法,分别是使用cJSON 库和Jansson 库,这两种库都提供了丰富的API,可以方便地解析、生成和操作JSON数据,根据具体需求选择合适的库即可。
以上内容就是解答有关linux c解析json的详细内容了,我相信这篇文章可以为您解决一些疑惑,有任何问题欢迎留言反馈,谢谢阅读。
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/63006.html