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")) ;

}

执行结果:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值