我正在从URL获取天气信息。
weather = urllib2.urlopen('url') wjson = weather.read()
我得到的是:
{ "data": { "current_condition": [{ "cloudcover": "0", "humidity": "54", "observation_time": "08:49 AM", "precipMM": "0.0", "pressure": "1025", "temp_C": "10", "temp_F": "50", "visibility": "10", "weatherCode": "113", "weatherDesc": [{ "value": "Sunny" }], "weatherIconUrl": [{ "value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" }], "winddir16Point": "E", "winddirDegree": "100", "windspeedKmph": "22", "windspeedMiles": "14" }] } }
如何访问所需的任何元素?
如果我这样做:print wjson['data']['current_condition']['temp_C']我收到错误消息:
print wjson['data']['current_condition']['temp_C']
字符串索引必须是整数,而不是str。
import json weather = urllib2.urlopen('url') wjson = weather.read() wjdata = json.loads(wjson) print wjdata['data']['current_condition'][0]['temp_C']
您从url中获得的是一个json字符串。而且您不能直接用索引解析它。您应该将其转换为dict json.loads,然后可以使用index对其进行解析。
json.loads
与其使用.read()中间方式将其保存到内存,然后将其读取为json,不如json直接从文件中加载它:
.read()
json
wjdata = json.load(urllib2.urlopen('url'))