Python 访问 JSON 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16129652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing JSON elements
提问by doniyor
I am getting the weather information from a URL.
我正在从 URL 获取天气信息。
weather = urllib2.urlopen('url')
wjson = weather.read()
and what I am getting is:
我得到的是:
{
"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?
如何访问我想要的任何元素?
if I do: print wjson['data']['current_condition']['temp_C']I am getting error saying:
如果我这样做:print wjson['data']['current_condition']['temp_C']我收到错误消息:
string indices must be integers, not str.
字符串索引必须是整数,而不是 str。
采纳答案by Yarkee
import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']
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.loadsand then you can parse it with index.
你从 url 得到的是一个 json 字符串。而且你不能直接用索引解析它。您应该将其转换为 dict by json.loads,然后您可以使用索引解析它。
Instead of using .read()to intermediately save it to memory and then read it to json, allow jsonto load it directly from the file:
允许直接从文件加载它,而不是使用.read()将其中间保存到内存然后读取到:jsonjson
wjdata = json.load(urllib2.urlopen('url'))
回答by alecxe
回答by HazimoRa3d
'temp_C' is a key inside dictionary that is inside a list that is inside a dictionary
'temp_C' 是字典中的一个键,它位于字典中的列表中
This way works:
这种方式有效:
wjson['data']['current_condition'][0]['temp_C']
>> '10'
回答by Alok Tiwari
Another alternative way using get method with requests:
对请求使用 get 方法的另一种替代方法:
import requests
wjdata = requests.get('url').json()
print wjdata.get('data').get('current_condition')[0].get('temp_C')
回答by Deividson Calixto
Just for more one option...You can do it this way too:
只是为了更多的选择......你也可以这样做:
MYJSON = {
'username': 'gula_gut',
'pics': '/0/myfavourite.jpeg',
'id': '1'
}
#changing username
MYJSON['username'] = 'calixto'
print(MYJSON['username'])
I hope this can help.
我希望这会有所帮助。

