cjson解析下面数据{ "name": "sys", "type": "table", "data": [ { "name": "dbc_path", "type": "string", "data": "/usrdata/dbc/GB-EP40_CAN_r5_v1.0.dbc" }, { "name": "first_boot", "type": "unsigned", "data": "0" }, ] }
时间: 2023-07-08 21:42:55 浏览: 165
解析这个 JSON 数据需要使用 cjson 库,可以使用以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main()
{
const char *json_data = "{ \"name\": \"sys\", \"type\": \"table\", \"data\": [ { \"name\": \"dbc_path\", \"type\": \"string\", \"data\": \"/usrdata/dbc/GB-EP40_CAN_r5_v1.0.dbc\" }, { \"name\": \"first_boot\", \"type\": \"unsigned\", \"data\": \"0\" } ] }";
cJSON *root = cJSON_Parse(json_data);
if (root == NULL) {
printf("Error before: [%s]\n", cJSON_GetErrorPtr());
return 1;
}
cJSON *name = cJSON_GetObjectItem(root, "name");
printf("name: %s\n", name->valuestring);
cJSON *type = cJSON_GetObjectItem(root, "type");
printf("type: %s\n", type->valuestring);
cJSON *data = cJSON_GetObjectItem(root, "data");
int size = cJSON_GetArraySize(data);
printf("data size: %d\n", size);
for (int i = 0; i < size; i++) {
cJSON *item = cJSON_GetArrayItem(data, i);
cJSON *name = cJSON_GetObjectItem(item, "name");
printf("item name: %s\n", name->valuestring);
cJSON *type = cJSON_GetObjectItem(item, "type");
printf("item type: %s\n", type->valuestring);
cJSON *data = cJSON_GetObjectItem(item, "data");
printf("item data: %s\n", data->valuestring);
}
cJSON_Delete(root);
return 0;
}
```
输出结果:
```
name: sys
type: table
data size: 2
item name: dbc_path
item type: string
item data: /usrdata/dbc/GB-EP40_CAN_r5_v1.0.dbc
item name: first_boot
item type: unsigned
item data: 0
```
阅读全文