91

我从 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']我收到错误消息:

字符串索引必须是整数,而不是 str。

4

8 回答 8

137
import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']

你从 url 得到的是一个 json 字符串。而且你不能直接用索引解析它。您应该将其转换为 dict byjson.loads然后您可以使用 index.html 解析它。

允许直接从文件中加载它,而不是使用.read()中间将它保存到内存然后读取它:jsonjson

wjdata = json.load(urllib2.urlopen('url'))
于 2013-04-21T09:20:50.170 回答
32

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

import requests
wjdata = requests.get('url').json()
print wjdata['data']['current_condition'][0]['temp_C']
于 2013-04-21T10:05:57.030 回答
8

'temp_C' 是字典内的键,位于字典内的列表内

这种方式有效:

wjson['data']['current_condition'][0]['temp_C']
>> '10'
于 2017-09-19T17:39:33.597 回答
2

你也可以这样做:

MYJSON = {
    'username': 'gula_gut',
    'pics': '/0/myfavourite.jpeg',
    'id': '1'
}

#changing username
MYJSON['username'] = 'calixto'
print(MYJSON['username'])
于 2020-02-06T22:26:58.893 回答
1

将 get 方法与请求一起使用的另一种替代方法:

import requests
wjdata = requests.get('url').json()
print wjdata.get('data').get('current_condition')[0].get('temp_C')
于 2019-12-27T08:19:25.830 回答
1
import json

# some JSON:
json_str =  '{ "name":"Sarah", "age":25, "city":"Chicago"}'

# parse json_str:
json = json.loads(json_str)

# get tags from json   
tags = []
for tag in json:
    tags.append(tag)
  

# print each tag name e your content
for i in range(len(tags)):
    print(tags[i] + ': ' + str(json[tags[i]]))
于 2021-01-09T15:24:08.373 回答
1

我做了这个方法来深入导航 Json

def filter_dict(data: dict, extract):
    try:
        if isinstance(extract, list):
            while extract:
                if result := filter_dict(data, extract.pop(0)):
                    return result
        shallow_data = data.copy()
        for key in extract.split('.'):
            if str(key).isnumeric():
                key = int(key)
            shallow_data = shallow_data[key]
        return shallow_data
    except (IndexError, KeyError, AttributeError):
        return None

filter_dict(wjdata, 'data.current_condition.0.temp_C')
# 10

Using the multiple fields:
filter_dict(wjdata, ['data.current_condition.0.temp_C', 'data.current_condition.1.temp_C']) This working as a OR when take the first element found

# 10

于 2021-02-19T10:33:13.880 回答
0

就像其他答案指出的那样,这个问题的公认答案似乎忽略了原始发布者的数据结构误解。

主要问题似乎是原始解决方案将 JSON 纯粹视为字典,而实际上它是...

列表中的字典,字典中的字典,字典中的字典

因此, ['data']需要访问字典的顶级键:值对, ['current_conditions']访问下一级字典,然后[0]必须用于访问列表的第一个元素(只有一个元素)。

只有这样才能['temp_C']访问该键的实际值并检索数据。

x={
  "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"
                },
                {
                    "cloudcover": "0",
                    "humidity": "54",
                    "observation_time": "08:49 AM",
                    "precipMM": "0.0",
                    "pressure": "1025",
                    "temp_C": "5",
                    "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(x['data']['current_condition'][0]['weatherDesc'][0]['value'])

# results in 'Sunny' 

在回答评论中的另一个问题时,

“假设有更多当前条件条目,有没有办法在不知道索引的情况下做到这一点?”

假设有许多current_condition条目,您不太可能只想要一个值,或者如果您这样做了,那么您可能会有另一条信息来定位该特定值(即位置或其他东西)。

假设您的数据集名为x,即x = {"data": ...}

如果您想要所有current_condition条目,您可以使用以下命令遍历列表 (of current_conditions):

y = []

for index in range(0,len(x['data']['current_condition']))
   y.append(x['data']['current_condition'][index]['temp_C'])
于 2021-07-20T08:32:44.920 回答