C语言cjson解析数组
时间: 2025-07-10 08:07:18 浏览: 6
在C语言中使用 cJSON 库解析 JSON 数组时,通常需要遍历数组中的各个元素,并提取其中的键值对。以下是一个完整的示例代码,展示如何解析一个包含多个对象的 JSON 数组。
假设我们有如下结构的 JSON 数据:
```json
{
"uart_config": [
{
"baudrate": 9600,
"dbit": 8,
"parity": 0,
"sbit": 1
},
{
"baudrate": 115200,
"dbit": 7,
"parity": 1,
"sbit": 2
}
]
}
```
### 示例代码
```c
#include "cJSON.h"
#include <stdio.h>
int main() {
// 假设这是从文件或网络接收到的 JSON 字符串
const char *json_str = "{"
"\"uart_config\": ["
"{"
"\"baudrate\": 9600,"
"\"dbit\": 8,"
"\"parity\": 0,"
"\"sbit\": 1"
"},"
"{"
"\"baudrate\": 115200,"
"\"dbit\": 7,"
"\"parity\": 1,"
"\"sbit\": 2"
"}"
"]"
"}";
// 解析 JSON 字符串
cJSON *root = cJSON_Parse(json_str);
if (!root) {
printf("Error before: %s\n", cJSON_GetErrorPtr());
return -1;
}
// 获取 uart_config 数组
cJSON *uart_config = cJSON_GetObjectItemCaseSensitive(root, "uart_config");
if (uart_config && cJSON_IsArray(uart_config)) {
int array_size = cJSON_GetArraySize(uart_config);
for (int i = 0; i < array_size; i++) {
cJSON *item = cJSON_GetArrayItem(uart_config, i);
if (item && cJSON_IsObject(item)) {
cJSON *baudrate = cJSON_GetObjectItemCaseSensitive(item, "baudrate");
cJSON *dbit = cJSON_GetObjectItemCaseSensitive(item, "dbit");
cJSON *parity = cJSON_GetObjectItemCaseSensitive(item, "parity");
cJSON *sbit = cJSON_GetObjectItemCaseSensitive(item, "sbit");
if (baudrate && dbit && parity && sbit) {
printf("Item %d:\n", i + 1);
printf(" baudrate: %d\n", baudrate->valueint);
printf(" dbit: %d\n", dbit->valueint);
printf(" parity: %d\n", parity->valueint);
printf(" sbit: %d\n", sbit->valueint);
}
}
}
}
// 清理内存
cJSON_Delete(root);
return 0;
}
```
### 说明
- 使用 `cJSON_Parse` 将 JSON 字符串解析为 cJSON 对象树。
- 使用 `cJSON_GetObjectItemCaseSensitive` 获取顶层对象中的 `uart_config` 数组。
- 判断是否为数组类型后,使用 `cJSON_GetArraySize` 获取数组长度,并通过 `cJSON_GetArrayItem` 遍历每个子对象。
- 对每个子对象再次使用 `cJSON_GetObjectItemCaseSensitive` 提取字段并打印其整数值。
- 最后调用 `cJSON_Delete` 释放内存[^1]。
### 编译与运行
确保已将 cJSON 源码(`cJSON.c` 和 `cJSON.h`)添加到项目中,并在编译时包含相应的头文件路径。例如:
```bash
gcc main.c cJSON.c -o parse_json_array
./parse_json_array
```
输出结果应为:
```
Item 1:
baudrate: 9600
dbit: 8
parity: 0
sbit: 1
Item 2:
baudrate: 115200
dbit: 7
parity: 1
sbit: 2
```
阅读全文
相关推荐


















