我从URL获取天气信息.
weather = urllib2.urlopen('url')
wjson = weather.read()
Run Code Online (Sandbox Code Playgroud)
而我得到的是:
{
"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"
}]
}
}
Run Code Online (Sandbox Code Playgroud)
如何访问我想要的任何元素?
如果我这样做:print wjson['data']['current_condition']['temp_C']我收到错误说:
字符串索引必须是整数,而不是str.
Yar*_*kee 91
import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']
Run Code Online (Sandbox Code Playgroud)
你从网址得到的是一个json字符串.并且您无法直接使用索引解析它.你应该将它转换为dict json.loads,然后你可以用索引解析它.
而不是使用.read()中间将其保存到内存然后读取它json,允许json直接从文件加载它:
wjdata = json.load(urllib2.urlopen('url'))
Run Code Online (Sandbox Code Playgroud)
ale*_*cxe 23
这是使用请求的替代解决方案:
import requests
wjdata = requests.get('url').json()
print wjdata['data']['current_condition'][0]['temp_C']
Run Code Online (Sandbox Code Playgroud)
'temp_C'是字典内的键,该键在字典内的列表内
这种方式有效:
wjson['data']['current_condition'][0]['temp_C']
>> '10'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
156565 次 |
| 最近记录: |