cjson读取json文件_json文件解析

/*reference documentationhttps://blog.csdn.net/stsahana/article/details/79638992

https://blog.csdn.net/fengxinlinux/article/details/53121287

*/#include#include#include#include#include"cJSON.h"

char *json_file_path = "./railwayFence.json";char *json_loader(char *path)

{

FILE*f;longlen;char *content;

f=fopen(path,"rb");

fseek(f,0,SEEK_END);

len=ftell(f);

fseek(f,0,SEEK_SET);

content=(char*)malloc(len+1);

fread(content,1,len,f);

fclose(f);returncontent;

}int main(void)

{char *json_str =json_loader(json_file_path);

cJSON*root=cJSON_Parse(json_str);if (!root) {

printf("Error before: [%s]\n",cJSON_GetErrorPtr());

}//railwayFence array

cJSON *railwayFenceArray = cJSON_GetObjectItem(root, "railwayFence");if(!railwayFenceArray){

printf("Error before: [%s]\n",cJSON_GetErrorPtr());

}int railwayFence_array_size =cJSON_GetArraySize(railwayFenceArray);

printf("railwayFence array size is %d\n",railwayFence_array_size);int i = 0;char *p =NULL;

cJSON*it;for(i=0; i< railwayFence_array_size; i++) {

cJSON*railwayFenceItem =cJSON_GetArrayItem(railwayFenceArray,i);

p=cJSON_PrintUnformatted(railwayFenceItem);

it=cJSON_Parse(p);if(!it)continue;

cJSON*areaName,*dangerType;

areaName= cJSON_GetObjectItem(it, "areaName");

printf("areaName is %s\n",areaName->valuestring);

dangerType= cJSON_GetObjectItem(it, "dangerType");

printf("dangerType is %s\n",dangerType->valuestring);//Coordinate array

cJSON *CoordinateArray = cJSON_GetObjectItem(railwayFenceItem, "coordinates");if(!CoordinateArray){

printf("Error before: [%s]\n",cJSON_GetErrorPtr());

}int Coordinate_array_size =cJSON_GetArraySize(CoordinateArray);

printf("Coordinate array size is %d\n",Coordinate_array_size);int j = 0;char *q =NULL;

cJSON*jt;for(j=0; j< Coordinate_array_size; j++) {

cJSON*CoordinateItem =cJSON_GetArrayItem(CoordinateArray,j);

q=cJSON_PrintUnformatted(CoordinateItem);

jt=cJSON_Parse(q);if(!jt)continue;

cJSON*B,*L;

B= cJSON_GetObjectItem(jt, "B");

printf("B is %f\n",B->valuedouble);

L= cJSON_GetObjectItem(jt, "L");

printf("L is %f\n",L->valuedouble);free(q); cJSON_Delete(jt);

}free(p); cJSON_Delete(it);

}if(root) {

cJSON_Delete(root);//return 0;

}return 0;

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值