C语言使用josn库解析数据

首先 添加好百度下载的json库:

 代码演示:

#include <stdio.h>
/*
char *requestHead = "GET /area-to-weather?area=广州 HTTP/1.1\r\n"
                    "Host: ali-weather.showapi.com\r\n"
                    "Authorization: APPCODE d487d937315848af80710a06f4592fee\r\n\r\n";
                    */ 
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

//添加json 库文件 
#include "cJSON.h"

double get_double(cJSON *json, char *key)
{
	cJSON *value = cJSON_GetObjectItem(json,key);
	return cJSON_GetNumberValue(value);
}


char *get_string(cJSON *json, char *key)
{
	cJSON *value = cJSON_GetObjectItem(json,key);
	return cJSON_GetStringValue(value);
}



int  main()
{

    //1.打开获取json 数据 
    int fd = open("json.txt",O_RDWR);

    char  string[4096]={0}; 
    read(fd,string,4096);
    printf("%s\n",string);

   //解析JSON 数据包 
   cJSON *json = cJSON_Parse(string);
   if(json == NULL)
   {
       const char *err =  cJSON_GetErrorPtr();  
       fprintf(stderr,"cJSON_Parse fail:%s\n",err);
   }else 
   {
     printf("解析成功\n");
   }

		printf("success:%s\n",get_string(json, "success")) ;
		printf("city:%s\n",get_string(json, "city")) ;

    cJSON *info = cJSON_GetObjectItem( json,"info");

		printf("date:%s\n",get_string(info, "date")) ;
    printf("week:%s\n",get_string(info, "week")) ;
    printf("high:%s\n",get_string(info, "high")) ;
    printf("low:%s\n",get_string(info, "low")) ;

}

执行结果:

猜你喜欢

转载自blog.csdn.net/aaa2540567665/article/details/126506317