stm32摘取中间字符串,获取心知天气,不用cjson文件包

本文展示了如何使用C语言的字符串处理函数从给定的JSON数据中提取日期、天气状况、最高气温、最低气温和湿度等信息,避免了使用CJSON库,简化了代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串摘取在C语言中一直具有很高的地位,以获取心知天气中的信息为例

{"results":[{"location":{"id":"WTSQQYHVQ973","name":"Nanjing","country":"CN","path":"Nanjing,Nanjing,Jiangsu,China","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},"daily":[
{"date":"2022-07-13","text_day":"Cloudy","code_day":"4","text_night":"Cloudy","code_night":"4","high":"39","low":"29",
"rainfall":"0.00","precip":"0.00","wind_direction":"W","wind_direction_degree":"270","wind_speed":"32.8","wind_scale":"5","humidity":"66"},
{"date":"2022-07-14","text_day":"Cloudy","code_day":"4","text_night":"Cloudy","code_night":"4","high":"39","low":"30",
"rainfall":"0.00","precip":"0.00","wind_direction":"W","wind_direction_degree":"270","wind_speed":"23.4","wind_scale":"4","humidity":"67"},
{"date":"2022-07-15","text_day":"Cloudy","code_day":"4","text_night":"Cloudy","code_night":"4","high":"37","low":"28",
"rainfall":"0.00","precip":"0.00","wind_direction":"NW","wind_direction_degree":"315","wind_speed":"15.3","wind_scale":"3","humidity":"71"}],
"last_update":"2022-07-13T08:00:00+08:00"}]}

当需要获取其中的日期,天气,最高温度,最低温度,以及最近更新时间等代码如下,使用C语言操作字符串指令,能够有效的获取天气,避免了使用CJSON文件包,省却了大量的代码。

	char *s = NULL;
	char *str[3] = {NULL,NULL,NULL};
	uint32_t te = 0;
	
	str[0] = strstr((char*)data,"date"); //摘取第一个date后的所有字符串放入str[0]
	str[1] = strstr(str[0]+10,"date"); //摘取 str[0]+10 后第一个data 刚好是第二个date
	str[2] = strstr(str[1]+10,"date"); //摘取 str[1]+10 后第一个data 刚好是第三个date
	
	for(uint8_t i=0;i<3;i++){   
		s = strstr((char*)str[i],"date"); // 
		sscanf(s+7,"%[^\"]",Weather_Data[i].Date);
	}
	
	for(uint8_t i=0;i<3;i++){
		s = strstr((char*)str[i],"code_day");
		sscanf(s+11,"%u",&Weather_Data[i].Weather);
	}
	
	for(uint8_t i=0;i<3;i++){
		s = strstr((char*)str[i],"high");
		sscanf(s+7,"%u",&Weather_Data[i].Temp_H);
	}
	
	for(uint8_t i=0;i<3;i++){
		s = strstr((char*)str[i],"low");
		sscanf(s+6,"%u",&Weather_Data[i].Temp_L);
	}
	
	for(uint8_t i=0;i<3;i++){
		s = strstr((char*)str[i],"humidity");
		sscanf(s+11,"%u",&Weather_Data[i].Humi);
	}
	
	for(uint8_t i=0;i<3;i++){
		s = strstr((char*)str[i],"wind_scale");
		sscanf(s+13,"%u",&Weather_Data[i].Wind);
	}
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值