使用cjson写出{ "interlock_toggle_relation":{ "type":"1", "remote":[ "CTRL+A", "ALT+B" ], "local":[ "CTRL+A", "ALT+B" ] } }的解析代码,linux
时间: 2024-01-13 12:03:16 浏览: 22
使用cjson库解析JSON数据的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"
int main() {
// JSON字符串
char json_str[] = "{ \"interlock_toggle_relation\":{ \"type\":\"1\", \"remote\":[ \"CTRL+A\", \"ALT+B\" ], \"local\":[ \"CTRL+A\", \"ALT+B\" ] } }";
// 解析JSON
cJSON *root = cJSON_Parse(json_str);
if (root == NULL) {
printf("Error before: [%s]\n", cJSON_GetErrorPtr());
return 1;
}
// 获取interlock_toggle_relation对象
cJSON *toggle_relation = cJSON_GetObjectItem(root, "interlock_toggle_relation");
if (toggle_relation == NULL) {
printf("Failed to get interlock_toggle_relation\n");
cJSON_Delete(root);
return 1;
}
// 获取type值
cJSON *type = cJSON_GetObjectItem(toggle_relation, "type");
if (type == NULL) {
printf("Failed to get type\n");
cJSON_Delete(root);
return 1; }
printf("type: %s\n", type->valuestring);
// 获取remote数组
cJSON *remote = cJSON_GetObjectItem(toggle_relation, "remote");
if (remote == NULL) {
printf("Failed to get remote\n");
cJSON_Delete(root);
return 1;
}
printf("remote: ");
int i;
for (i = 0; i < cJSON_GetArraySize(remote); i++) {
cJSON *item = cJSON_GetArrayItem(remote, i);
printf("%s ", item->valuestring);
}
printf("\n");
// 获取local数组
cJSON *local = cJSON_GetObjectItem(toggle_relation, "local");
if (local == NULL) {
printf("Failed to get local\n");
cJSON_Delete(root);
return 1;
}
printf("local: ");
for (i = 0; i < cJSON_GetArraySize(local); i++) {
cJSON *item = cJSON_GetArrayItem(local, i);
printf("%s ", item->valuestring);
}
printf("\n");
// 释放内存
cJSON_Delete(root);
return 0;
}
```
编译运行上述代码,可以得到以下输出:
```
type: 1
remote: CTRL+A ALT+B
local: CTRL+A ALT+B
```