cJSON库的下载

cJSON是一个基于C的JSON解析库,这个库非常简单,只有cJSON.c和cJSON.h两个文件,支持JSON的解析和封装,需要调用时,只需要#include "cJSON.h"就可以使用了,

只包含键值对的JSON字符串解析

JSON字符串:

{
"name": "Andy", //键值对1
"age": 20 //键值对2
}

这个JSON对象只有两个键值对,键name对应字符串Andy,键age对应数字20。

void Parse_Str1(void)
{
char str1[] = "{\"name\":\"Andy\",\"age\":20}";
cJSON *str1_json, *str1_name, *str1_age;
printf("str1:%s\n\n",str1);
str1_json = cJSON_Parse(str1); //创建JSON解析对象,返回JSON格式是否正确
if (!str1_json)
{
printf("JSON格式错误:%s\n\n", cJSON_GetErrorPtr()); //输出json格式错误信息
}
else
{
printf("JSON格式正确:\n%s\n\n",cJSON_Print(str1_json) );
str1_name = cJSON_GetObjectItem(str1_json, "name"); //获取name键对应的值的信息
if (str1_name->type == cJSON_String)
{
printf("姓名:%s\r\n", str1_name->valuestring);
}
str1_age = cJSON_GetObjectItem(str1_json, "age"); //获取age键对应的值的信息
if(str1_age->type==cJSON_Number)
{
printf("年龄:%d\r\n", str1_age->valueint);
}
cJSON_Delete(str1_json);//释放内存
}
}

运行结果:

包含数组的JSON字符串解析

JSON字符串:

{
"location": [{
"name": "Faye",
"address": "北京"
},
{
"name": "Andy",
"address": "香港"
}
],
"time": "2018-11-17"
}

解析函数:

void Parse_Str2(void)
{ char str2[] = "{\"location\":[{\"name\":\"Faye\",\"address\":\"北京\"},{\"name\":\"Andy\",\"address\":\"香港\"}],\"time\":\"2018-11-17\"}"; cJSON *root = 0;
cJSON *loc_json = 0;
cJSON *name1_json,*name2_json;
char *time_str, *str_tmp; root = cJSON_Parse(str2);
if(!root)
printf("str2 JSON格式错误:%s \r\n", cJSON_GetErrorPtr());
else
{
printf("str2 JSON格式正确:\n%s\n",cJSON_Print(root));
time_str = cJSON_GetObjectItem(root,"time")->valuestring;//time键值对
printf("time:%s\n", time_str); loc_json = cJSON_GetObjectItem(root,"location");
if(loc_json)
{
name1_json = cJSON_GetArrayItem(loc_json,0); //数组第0个元素
str_tmp = cJSON_GetObjectItem(name1_json, "name")->valuestring;//name键对应的值
printf("name1 is : %s \r\n", str_tmp);
str_tmp = cJSON_GetObjectItem(name1_json, "address")->valuestring;//addr1键对应的值
printf("addr1 is : %s \r\n", str_tmp); name2_json = cJSON_GetArrayItem(loc_json,1); //数组第1个元素
str_tmp = cJSON_GetObjectItem(name2_json, "name")->valuestring;
printf("name2 is : %s \r\n", str_tmp);
str_tmp = cJSON_GetObjectItem(name2_json, "address")->valuestring;
printf("addr2 is : %s \r\n", str_tmp);
}
}
cJSON_Delete(loc_json);
}

运行结果:

北京时间JSON数据解析

api地址:

http://api.k780.com:88/?app=life.time&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json

JSON字符串:

{
"success": "1",
"result": {
"timestamp": "1543922613",
"datetime_1": "2018-12-04 19:23:33",
"datetime_2": "2018年12月04日 19时23分33秒",
"week_1": "2",
"week_2": "星期二",
"week_3": "周二",
"week_4": "Tuesday"
}
}

解析函数:

void Parse_BJ_Time(void)
{
char bj_time_str[] = "{\"success\":\"1\",\"result\":{\"timestamp\":\"1542456793\",\"datetime_1\":\"2018-11-17 20:13:13\",\"datetime_2\":\"2018年11月17日 20时13分13秒\",\"week_1\":\"6\",\"week_2\":\"星期六\",\"week_3\":\"周六\",\"week_4\":\"Saturday\"}}"; cJSON *root;
cJSON *result_json;
char *datetime, *week; root = cJSON_Parse(bj_time_str);
if(root)
{
printf("json格式正确:\n%s\n\n", cJSON_Print(root));
result_json = cJSON_GetObjectItem(root, "result"); //获取result键对应的值
if(result_json)
{
datetime = cJSON_GetObjectItem(result_json, "datetime_2")->valuestring;
printf("北京时间: %s \r\n", datetime);
week = cJSON_GetObjectItem(result_json, "week_2")->valuestring;
printf("星期: %s \r\n", week);
}
}
cJSON_Delete(root);
cJSON_Delete(result_json);
}

运行结果:

心知天气JSON数据解析

JSON字符串:

{
"results": [{
"location": {
"id": "WS10730EM8EV",
"name": "深圳",
"country": "CN",
"path": "深圳,深圳,广东,中国",
"timezone": "Asia/Shanghai",
"timezone_offset": "+08:00"
},
"daily": [{
"date": "2018-11-18",
"text_day": "多云",
"code_day": "4",
"text_night": "多云",
"code_night": "4",
"high": "26",
"low": "20",
"precip": "",
"wind_direction": "无持续风向",
"wind_direction_degree": "",
"wind_speed": "10",
"wind_scale": "2"
}, {
"date": "2018-11-19",
"text_day": "小雨",
"code_day": "13",
"text_night": "小雨",
"code_night": "13",
"high": "25",
"low": "20",
"precip": "",
"wind_direction": "无持续风向",
"wind_direction_degree": "",
"wind_speed": "10",
"wind_scale": "2"
}, {
"date": "2018-11-20",
"text_day": "小雨",
"code_day": "13",
"text_night": "小雨",
"code_night": "13",
"high": "25",
"low": "21",
"precip": "",
"wind_direction": "无持续风向",
"wind_direction_degree": "",
"wind_speed": "10",
"wind_scale": "2"
}],
"last_update": "2018-11-18T11:00:00+08:00"
}]
}

解析函数:

void parse_seniverse_weather(void)
{
char weather_str[] =
"{\"results\":[{\"location\":{\"id\":\"WS10730EM8EV\",\"name\":\"深圳\",\"country\":\"CN\",\"path\":\"深圳,深圳,广东,中国\",\"timezone\":\"Asia/Shanghai\",\"timezone_offset\":\"+08:00\"},\"daily\":[{\"date\":\"2018-11-18\",\"text_day\":\"多云\",\"code_day\":\"4\",\"text_night\":\"多云\",\"code_night\":\"4\",\"high\":\"26\",\"low\":\"20\",\"precip\":\"\",\"wind_direction\":\"无持续风向\",\"wind_direction_degree\":\"\",\"wind_speed\":\"10\",\"wind_scale\":\"2\"},{\"date\":\"2018-11-19\",\"text_day\":\"小雨\",\"code_day\":\"13\",\"text_night\":\"小雨\",\"code_night\":\"13\",\"high\":\"25\",\"low\":\"20\",\"precip\":\"\",\"wind_direction\":\"无持续风向\",\"wind_direction_degree\":\"\",\"wind_speed\":\"10\",\"wind_scale\":\"2\"},{\"date\":\"2018-11-20\",\"text_day\":\"小雨\",\"code_day\":\"13\",\"text_night\":\"小雨\",\"code_night\":\"13\",\"high\":\"25\",\"low\":\"21\",\"precip\":\"\",\"wind_direction\":\"无持续风向\",\"wind_direction_degree\":\"\",\"wind_speed\":\"10\",\"wind_scale\":\"2\"}],\"last_update\":\"2018-11-18T11:00:00+08:00\"}]}";
cJSON *root;
cJSON *results;
cJSON *last_update;
cJSON *loc_json, *daily_json;
cJSON *forecast_json;
char *loc_tmp, *weather_tmp, *update_tmp;
int i = 0; root = cJSON_Parse((const char*)weather_str);
if(root)
{
// printf("JSON格式正确:\n%s\n\n",cJSON_Print(root)); //输出json字符串
results = cJSON_GetObjectItem(root, "results");
results = cJSON_GetArrayItem(results,0);
if(results)
{
loc_json = cJSON_GetObjectItem(results, "location"); //得到location键对应的值,是一个对象 loc_tmp = cJSON_GetObjectItem(loc_json, "id") -> valuestring;
printf("城市ID:%s\n",loc_tmp);
loc_tmp = cJSON_GetObjectItem(loc_json, "name") -> valuestring;
printf("城市名称:%s\n",loc_tmp);
loc_tmp = cJSON_GetObjectItem(loc_json, "timezone") -> valuestring;
printf("城市时区:%s\n\n",loc_tmp); daily_json = cJSON_GetObjectItem(results, "daily");
if(daily_json)
{
for(i = 0; i < 3; i++)
{
forecast_json = cJSON_GetArrayItem(daily_json, i);
weather_tmp = cJSON_GetObjectItem(forecast_json, "date") -> valuestring;
printf("日期:%s\r\n", weather_tmp);
weather_tmp = cJSON_GetObjectItem(forecast_json, "code_day") -> valuestring;
printf("白天天气代码:%s\r\n", weather_tmp);
weather_tmp = cJSON_GetObjectItem(forecast_json, "code_night") -> valuestring;
printf("晚上天气代码:%s\r\n", weather_tmp);
weather_tmp = cJSON_GetObjectItem(forecast_json, "high") -> valuestring;
printf("最高温度:%s\r\n", weather_tmp);
weather_tmp = cJSON_GetObjectItem(forecast_json, "low") -> valuestring;
printf("最低温度:%s\r\n", weather_tmp);
weather_tmp = cJSON_GetObjectItem(forecast_json, "wind_direction_degree") -> valuestring;
printf("风向角度:%s\r\n", weather_tmp);
weather_tmp = cJSON_GetObjectItem(forecast_json, "wind_scale") -> valuestring;
printf("风力:%s\r\n\n", weather_tmp);
}
}
else
printf("daily json格式错误\r\n");
last_update = cJSON_GetObjectItem(results, "last_update");
update_tmp = last_update->valuestring;
if(last_update)
{
printf("更新时间:%s\r\n", update_tmp);
}
}
else
{
printf("results格式错误:%s\r\n", cJSON_GetErrorPtr());
}
}
else
{
printf("JSON格式错误\r\n");
}
cJSON_Delete(root);
cJSON_Delete(results);
}

运行结果:

和风天气数据解析

JSON字符串:

{
"HeWeather6": [{
"basic": {
"cid": "CN101010700",
"location": "昌平",
"parent_city": "北京",
"admin_area": "北京",
"cnty": "中国",
"lat": "40.21808624",
"lon": "116.23590851",
"tz": "+8.00"
},
"update": {
"loc": "2018-11-21 21:45",
"utc": "2018-11-21 13:45"
},
"status": "ok",
"daily_forecast": [{
"cond_code_d": "100",
"cond_code_n": "100",
"cond_txt_d": "晴",
"cond_txt_n": "晴",
"date": "2018-11-21",
"hum": "21",
"mr": "16:02",
"ms": "04:27",
"pcpn": "0.0",
"pop": "0",
"pres": "1030",
"sr": "07:08",
"ss": "16:53",
"tmp_max": "9",
"tmp_min": "-3",
"uv_index": "5",
"vis": "10",
"wind_deg": "323",
"wind_dir": "西北风",
"wind_sc": "1-2",
"wind_spd": "4"
}, {
"cond_code_d": "100",
"cond_code_n": "101",
"cond_txt_d": "晴",
"cond_txt_n": "多云",
"date": "2018-11-22",
"hum": "21",
"mr": "16:36",
"ms": "05:33",
"pcpn": "0.0",
"pop": "0",
"pres": "1030",
"sr": "07:09",
"ss": "16:52",
"tmp_max": "8",
"tmp_min": "-4",
"uv_index": "3",
"vis": "20",
"wind_deg": "35",
"wind_dir": "东北风",
"wind_sc": "1-2",
"wind_spd": "5"
}, {
"cond_code_d": "101",
"cond_code_n": "100",
"cond_txt_d": "多云",
"cond_txt_n": "晴",
"date": "2018-11-23",
"hum": "23",
"mr": "17:15",
"ms": "06:41",
"pcpn": "0.0",
"pop": "16",
"pres": "1024",
"sr": "07:10",
"ss": "16:52",
"tmp_max": "7",
"tmp_min": "-2",
"uv_index": "2",
"vis": "20",
"wind_deg": "305",
"wind_dir": "西北风",
"wind_sc": "1-2",
"wind_spd": "3"
}]
}]
}

解析函数:

//解析和风天气,格式和心知天气非常像
void parse_heweather(void)
{
char heweather_str[] = "{\"HeWeather6\":[{\"basic\":{\"cid\":\"CN101010700\",\"location\":\"昌平\",\"parent_city\":\"北京\",\"admin_area\":\"北京\",\"cnty\":\"中国\",\"lat\":\"40.21808624\",\"lon\":\"116.23590851\",\"tz\":\"+8.00\"},\"update\":{\"loc\":\"2018-11-21 21:45\",\"utc\":\"2018-11-21 13:45\"},\"status\":\"ok\",\"daily_forecast\":[{\"cond_code_d\":\"100\",\"cond_code_n\":\"100\",\"cond_txt_d\":\"晴\",\"cond_txt_n\":\"晴\",\"date\":\"2018-11-21\",\"hum\":\"21\",\"mr\":\"16:02\",\"ms\":\"04:27\",\"pcpn\":\"0.0\",\"pop\":\"0\",\"pres\":\"1030\",\"sr\":\"07:08\",\"ss\":\"16:53\",\"tmp_max\":\"9\",\"tmp_min\":\"-3\",\"uv_index\":\"5\",\"vis\":\"10\",\"wind_deg\":\"323\",\"wind_dir\":\"西北风\",\"wind_sc\":\"1-2\",\"wind_spd\":\"4\"},{\"cond_code_d\":\"100\",\"cond_code_n\":\"101\",\"cond_txt_d\":\"晴\",\"cond_txt_n\":\"多云\",\"date\":\"2018-11-22\",\"hum\":\"21\",\"mr\":\"16:36\",\"ms\":\"05:33\",\"pcpn\":\"0.0\",\"pop\":\"0\",\"pres\":\"1030\",\"sr\":\"07:09\",\"ss\":\"16:52\",\"tmp_max\":\"8\",\"tmp_min\":\"-4\",\"uv_index\":\"3\",\"vis\":\"20\",\"wind_deg\":\"35\",\"wind_dir\":\"东北风\",\"wind_sc\":\"1-2\",\"wind_spd\":\"5\"},{\"cond_code_d\":\"101\",\"cond_code_n\":\"100\",\"cond_txt_d\":\"多云\",\"cond_txt_n\":\"晴\",\"date\":\"2018-11-23\",\"hum\":\"23\",\"mr\":\"17:15\",\"ms\":\"06:41\",\"pcpn\":\"0.0\",\"pop\":\"16\",\"pres\":\"1024\",\"sr\":\"07:10\",\"ss\":\"16:52\",\"tmp_max\":\"7\",\"tmp_min\":\"-2\",\"uv_index\":\"2\",\"vis\":\"20\",\"wind_deg\":\"305\",\"wind_dir\":\"西北风\",\"wind_sc\":\"1-2\",\"wind_spd\":\"3\"}]}]}"; cJSON *root;
cJSON *results;
cJSON *basic_json, *update_json, *forecast_json;
cJSON *daily_json; int i = 0;
char *basic_tmp, *update_tmp, *status_tmp, *weather_tmp;
root = cJSON_Parse(heweather_str);
if(root)
{
results = cJSON_GetObjectItem(root, "HeWeather6"); //HeWeather键对应的值,是一个数组
results = cJSON_GetArrayItem(results,0);
if(results)
{
basic_json = cJSON_GetObjectItem(results, "basic");
if(basic_json)
{
basic_tmp = cJSON_GetObjectItem(basic_json, "cid") -> valuestring;
printf("城市ID:%s\n",basic_tmp);
basic_tmp = cJSON_GetObjectItem(basic_json, "location") -> valuestring;
printf("县级市:%s\n",basic_tmp);
basic_tmp = cJSON_GetObjectItem(basic_json, "parent_city") -> valuestring;
printf("地级市:%s\n",basic_tmp);
basic_tmp = cJSON_GetObjectItem(basic_json, "admin_area") -> valuestring;
printf("所属省:%s\n",basic_tmp);
basic_tmp = cJSON_GetObjectItem(basic_json, "lat") -> valuestring;
printf("纬度:%s\n",basic_tmp);
basic_tmp = cJSON_GetObjectItem(basic_json, "lon") -> valuestring;
printf("经度:%s\n\n",basic_tmp);
}
update_json = cJSON_GetObjectItem(results, "update");
if(update_json)
{
update_tmp = cJSON_GetObjectItem(update_json, "loc") -> valuestring;
printf("更新时间:%s(所在地时间)\n", update_tmp);
update_tmp = cJSON_GetObjectItem(update_json, "utc") -> valuestring;
printf("更新时间:%s(世界时间)\n\n", update_tmp);
}
status_tmp = cJSON_GetObjectItem(results, "status") -> valuestring;
printf("解析状态:%s\n\n", status_tmp);
daily_json = cJSON_GetObjectItem(results, "daily_forecast");
if(daily_json)
{
for(i = 0; i < 3; i++)
{
forecast_json = cJSON_GetArrayItem(daily_json, i);
weather_tmp = cJSON_GetObjectItem(forecast_json, "date") -> valuestring;
printf("日期:%s\r\n", weather_tmp);
weather_tmp = cJSON_GetObjectItem(forecast_json, "cond_txt_d") -> valuestring;
printf("白天天气:%s\r\n", weather_tmp);
weather_tmp = cJSON_GetObjectItem(forecast_json, "cond_txt_n") -> valuestring;
printf("晚上天气:%s\r\n", weather_tmp);
weather_tmp = cJSON_GetObjectItem(forecast_json, "tmp_max") -> valuestring;
printf("最高温度:%s\r\n", weather_tmp);
weather_tmp = cJSON_GetObjectItem(forecast_json, "tmp_min") -> valuestring;
printf("最低温度:%s\r\n", weather_tmp);
weather_tmp = cJSON_GetObjectItem(forecast_json, "wind_deg") -> valuestring;
printf("风向角度:%s\r\n", weather_tmp);
weather_tmp = cJSON_GetObjectItem(forecast_json, "wind_dir") -> valuestring;
printf("风向:%s\r\n", weather_tmp);
weather_tmp = cJSON_GetObjectItem(forecast_json, "wind_sc") -> valuestring;
printf("风力:%s\r\n\n", weather_tmp);
}
}
}
}
cJSON_Delete(root);
cJSON_Delete(results);
cJSON_Delete(basic_json);
cJSON_Delete(update_json);
cJSON_Delete(forecast_json);
cJSON_Delete(daily_json);
}

运行结果:

源码下载及实用的API地址:

  • 本项目CodeBlock工程源码下载:MyJSON

  • 在线JSON格式校验工具:bejson

  • 免费的天气api接口:天气API


历史精选文章:


欢迎大家关注我的个人博客

或微信扫码关注我的公众号

使用cJSON库解析JSON的更多相关文章

  1. 使用cJSON库解析和构建JSON字符串

    使用cJSON库解析和构建JSON字符串 前言 其实之前的两篇博文已经介绍了json格式和如何使用cJSON库来解析JSON: 使用cJSON库解析JSON JSON简介 当时在MCU平台上使用时,会 ...

  2. 使用QtScript库解析Json数组例子

    本文转载自:http://blog.sina.com.cn/s/blog_671732440100uwxh.html 使用qtscipt库解析json数组首先在工程文件中加 QT        += ...

  3. [置顶] cJSON库(构建json与解析json字符串)-c语言

     一.c语言获取json中的数据. 1.先要有cJOSN库,两个文件分别是cJSON.c和cJSON.h. 2.感性认识 char * json = "{ \"json\" ...

  4. SpringMVC Jackson 库解析 json 串属性名大小写自动转换问题

    问题描述 在项目开发中,当实体类和表中定义的某个字段为 RMBPrice,首字母是大写的,sql 查询出来的列名也是大写的 RMBPrice,但是使用 jquery 的 ajax 返回请求响应时却出错 ...

  5. jmespath库解析json

    在测试过程中,经常会去JSON中的某个值,jmespath可以是除了jsonpath的另外一种选择. 下面通过几个例子来说明jmespath在python的使用 jmespath python安装 非 ...

  6. Oracle 使用GSON库解析复杂json串

    在前文中讲到了如何使用JSON标准库解析json串,参考: Oracle解析复杂json的方法(转) 现补充一篇使用GSON库在Oracle中解析复杂json的方法. GSON串的使用教程参考官方文档 ...

  7. C语言cJSON库的使用,解析json数据格式

    C语言cJSON库的使用,解析json数据格式 摘自:https://www.cnblogs.com/piaoyang/p/9274925.html 对于c语言来说是没有字典这样的结构的,所以对于解析 ...

  8. 使用CJSON库实现XML与JSON格式的相互转化

    之前完成了一个两个平台对接的项目.由于这两个平台一个是使用json格式的数据,一个是使用xml格式的数据,要实现它们二者的对接就涉及到这两个数据格式的转化,在查阅相关资料的时候发现了这个CJSON库, ...

  9. 两种库解析、构造 JSON

    1.用CJSON库 1.1解析Json 需要解析的JSON文件: { "name":"Tsybius", , "sex_is_male":t ...

随机推荐

  1. [翻译] PPiAwesomeButton

    PPiAwesomeButton https://github.com/pepibumur/PPiAwesomeButton UIButton category with new methods to ...

  2. Laravel 实践之路: 数据库迁移与数据填充

    数据库迁移实际上就是对数据库库表的结构变化做版本控制,之前对数据库库表结构做修改的方式比较原始,比如说对某张库表新增了一个字段,都是直接在库表中执行alter table xxx add .. 的方式 ...

  3. September 07th 2017 Week 36th Thursday

    With the most true of yourself, can you meet the most suitable one. 用最真实的自己,才能遇见最合适的那个人. You are alw ...

  4. if 的一切

    第一种语法: if 条件: # @引号是为了把条件和结果分开. 结果1 # 一个Tab或者4个空格 @告诉程序满足上面的if条件才会执行结果1结果2 如果条件为真(True),执行结果1,然后执行结果 ...

  5. 在.NET中操作数字证书(新手教程)

    .NET为我们提供了操作数字证书的两个主要的类,分为为: System.Security.Cryptography.X509Certificates.X509Certificate2类, 每个这个类的 ...

  6. 使用 Bulk Copy 将大量数据复制到数据库

    如果一次要向数据库服务器提交多条记录 , 通常会执行多次Insert命令 , 这样就为要插入的每个记录执行一次与数据库服务器的往返 , 这就给服务器增加了压力 , 效率也大大的降低了... .Net  ...

  7. Perl之my与local

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/sunshoupo211/article/details/31745909    在函数定义中,使用m ...

  8. 真机测试出现INSTALL_FAILED_USER_RESTRICTED安装错误

    之前用小米测试的时候遇到一个问题,两个一样型号的手机一个能直接用Android Studio安装公司的项目一个却不可以,总是报INSTALL_FAILED_USER_RESTRICTED错误,具体见下 ...

  9. 在不升级 mysql 的情况下直接使用 mysql utf8 存储 超过三个字节的 emoji 表情

    由于现在数据库的版本是5.5.2,但是看网上说要直接存储emoji表情,需要升级到5.5.3然后把字符集设置为utf8mb4,但是升级数据库感觉属于敏感操作. 考虑了多久之后直接考虑使用正则来替换,但 ...

  10. 多线程之synchronized

    Java并发编程:synchronized 虽然多线程编程极大地提高了效率,但是也会带来一定的隐患.比如说两个线程同时往一个数据库表中插入不重复的数据,就可能会导致数据库中插入了相同的数据.今天我们就 ...