访问JSON元素

don*_*yor 65 python json

我从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)

  • 最好做`json.load(urllib2.urlopen('url'))`所以它直接加载它而不是中间保存到内存 (3认同)

ale*_*cxe 23

这是使用请求的替代解决方案:

import requests
wjdata = requests.get('url').json()
print wjdata['data']['current_condition'][0]['temp_C']
Run Code Online (Sandbox Code Playgroud)

  • 假设有更多当前条件条目,有没有办法在不知道索引的情况下返回它? (2认同)

Haz*_*a3d 6

'temp_C'是字典内的键,该键在字典内的列表内

这种方式有效:

wjson['data']['current_condition'][0]['temp_C']
>> '10'
Run Code Online (Sandbox Code Playgroud)