python进阶宝典14- json 数据处理

先看代码:

## 用 loads() 读取json,返回一个python字典
import json
stringJson = '{"name":"Zophie","iscat":true,"micecaught":0,"felineiq":null}'  # json字符串总是用双引号
jsonToPython = json.loads(stringJson)
print(jsonToPython)           # {'name': 'Zophie', 'iscat': True, 'micecaught': 0, 'felineiq': None}
# dumps() 输出 json 格式
pythonValue = {'name': 'Zophie', 'iscat': True, 'micecaught': 0, 'felineiq': None}
stringJson = json.dumps(pythonValue)
print(stringJson)


##  下载并处理天气预报数据
# 1. 命令行读取请求天气的位置     -- 处理 sys.argv
# 2. 从OpenWeatherMap.org 下载JSON天气数据   --调用 requests.get()
# 3. 讲JSON数据转成python数据结构   -- json.loads()
# 4. 打印未来两天的天气
# Prints the weather for a location from the command line.

import json, requests, sys
# Compute location from command ine arguments.
if len(sys.argv) < 2:
    print('Usage: quickWeather.py location')
    sys.exit()
location = ' '.join(sys.argv[1:])
# Download the JSON data from OpenWeatherMap.org's API.
url = 'http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=8ixCCFzlBB617YX7tONI2P5B\
&mcode=1C:6B:42:33:E8:A6:DC:A2:11:6E:26:EC:84:BD:42:E3:8E:6B:57:9A;com.example.administrator.jsontest' % (location)
response = requests.get(url)
response.raise_for_status()
# Load JSON data into a Python variable.
weatherData = json.loads(response.text)
print('Current weather in %s:' % (location) )
print(weatherData)
# w = weatherData['list']                # 根据具体数据打印
# print(w[0]['weather'][0]['main'])      # 根据具体数据打印

先说下,下面这个天气预报的例子不一定能跑出来。试验了下,几个国外的天气 api 访问不了,与网络控制有关;在网上找了几个号称免费的,验证下来都不行。 还是只有使用百度的API了。 

需要去注册一个百度API的开发密钥ak,具体步骤可参考此前文章:

Python使用百度地图API实现地点信息转换及房价指数热力地图     https://blog.csdn.net/ebzxw/article/details/80265796

另外,国家气象局的可以试一下,好像注册后要等48小时审核。

猜你喜欢

转载自blog.csdn.net/ebzxw/article/details/80369717