c语言json使用,cJSON使用(二)

a9ae38a756af

目录

实战举例

上文学习了cJSON库的一些理论知识,接下来开始进行实战.

从一个json文件中读取并解析这个文件.

代码实现

资源文件内容res.json:

{

"config_appl": "file",

"version": "0.1.0",

"resources": {

"key_p": "NA",

"key_n": "WO",

"key_e": "local",

"key_ze": "na",

"key_le": "na",

"key_name": "na",

"key_type": "file",

"key_ID": "na"

}

}

test.c代码:

#include

#include

#include

#include"cJSON.h"

char* read_file(const char *filename) {

FILE *file = NULL;

long length = 0;

char *content = NULL;

size_t read_chars = 0;

/* open in read binary mode */

file = fopen(filename, "rb");

if (file == NULL)

{

goto cleanup;

}

/* get the length */

if (fseek(file, 0, SEEK_END) != 0)

{

goto cleanup;

}

length = ftell(file);

if (length < 0)

{

goto cleanup;

}

if (fseek(file, 0, SEEK_SET) != 0)

{

goto cleanup;

}

/* allocate content buffer */

content = (char*)malloc((size_t)length + sizeof(""));

if (content == NULL)

{

goto cleanup;

}

/* read the file into memory */

read_chars = fread(content, sizeof(char), (size_t)length, file);

if ((long)read_chars != length)

{

free(content);

content = NULL;

goto cleanup;

}

content[read_chars] = '\0';

cleanup:

if (file != NULL)

{

fclose(file);

}

return content;

}

int main()

{

char *json_file;

cJSON * json_tmp;

cJSON * ch, *key_ch;

int size;

int kye_size;

int i, j;

//使用官网函数读取文件(test/common.c)

json_file = read_file("res.json");

//解析json

json_tmp = cJSON_Parse(json_file);

//获取当前key值数量

size = cJSON_GetArraySize(json_tmp);

printf("%d\n", size);

//判断数据类型

ch = json_tmp->child;

for(i = 0; i < size; i++){

printf("[num=%d] [type=%d]\n", i, ch->type);

ch = ch->next;

}

//打印每一个key值

ch = json_tmp->child;

for(i = 0; i < size; i++){

if(cJSON_IsObject(ch)){

kye_size = cJSON_GetArraySize(ch);

key_ch = ch->child;

printf("[num=%d ]\n", i);

printf("[key=%s]\n", ch->string);

printf("----------------------\n");

for(j = 0; j < kye_size; j++){

printf("[value_num=%d ]\n", j);

printf("[key=%s]\n[value=%s]\n", key_ch->string, key_ch->valuestring);

key_ch = key_ch->next;

}

printf("----------------------\n");

}else{

printf("[num=%d ]\n", i);

printf("[key=%s]\n[value=%s]\n", ch->string, ch->valuestring);

}

ch = ch->next;

}

}

编译执行命令:

gcc test.c cJSON.c -lm

运行结果:

a9ae38a756af

image.png

参考

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值