访问JSON元素 [英] Accessing JSON elements
问题描述
我正在从URL获取天气信息.
I am getting the weather information from a 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"
}]
}
}
如何访问所需的任何元素?
How can I access any element I want?
如果我这样做:print wjson['data']['current_condition']['temp_C']
我收到错误消息:
if I do: print wjson['data']['current_condition']['temp_C']
I am getting error saying:
字符串索引必须是整数,而不是str.
string indices must be integers, not str.
推荐答案
import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']
您从url中获得的是一个json字符串.而且您不能直接用索引解析它.
您应该通过json.loads
将其转换为字典,然后可以使用索引对其进行解析.
What you get from the url is a json string. And your can't parse it with index directly.
You should convert it to a dict by json.loads
and then you can parse it with index.
不是使用.read()
中间将其保存到内存中,然后将其读取到json
,而是允许json
直接从文件中加载它:
Instead of using .read()
to intermediately save it to memory and then read it to json
, allow json
to load it directly from the file:
wjdata = json.load(urllib2.urlopen('url'))
这篇关于访问JSON元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!