天天看點

使用cJSON庫解析JSON

cJSON庫的下載下傳

cJSON是一個基于C的JSON解析庫,這個庫非常簡單,隻有cJSON.c和cJSON.h兩個檔案,支援JSON的解析和封裝,需要調用時,隻需要

#include "cJSON.h"

就可以使用了,

隻包含鍵值對的JSON字元串解析

JSON字元串:

{
    "name": "Andy",      //鍵值對1
    "age": 20              //鍵值對2
}           
使用cJSON庫解析JSON

這個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);//釋放記憶體
    }
}           

運作結果:

使用cJSON庫解析JSON

包含數組的JSON字元串解析

{
    "location": [{
            "name": "Faye",
            "address": "北京"
        },
        {
            "name": "Andy",
            "address": "香港"
        }
    ],
    "time": "2018-11-17"
}           
使用cJSON庫解析JSON

解析函數:

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);
}           
使用cJSON庫解析JSON

中原標準時間JSON資料解析

api位址:

http://api.k780.com:88/?app=life.time&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=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);
}           
使用cJSON庫解析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);
}           
使用cJSON庫解析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);
}           
使用cJSON庫解析JSON

源碼下載下傳及實用的API位址:

  • 本項目CodeBlock工程源碼下載下傳: MyJSON
  • 線上JSON格式校驗工具: bejson
  • 免費的天氣api接口: 天氣API

曆史精選文章:

歡迎大家關注

我的個人部落格

或微信掃碼關注我的公衆号

使用cJSON庫解析JSON