Python 访问JSON元素

Python 访问JSON元素,python,json,Python,Json,我正在从一个URL获取天气信息 weather = urllib2.urlopen('url') wjson = weather.read() 我得到的是: { "data": { "current_condition": [{ "cloudcover": "0", "humidity": "54", "observation_time": "08:49 AM", "precipMM": "0.0",

我正在从一个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

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

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

wjdata = json.load(urllib2.urlopen('url'))

以下是另一种解决方案,使用:


“temp_C”是字典中的一个键,它位于字典中的列表中

这种方式有效:

wjson['data']['current_condition'][0]['temp_C']
>> '10'

对请求使用get方法的另一种替代方法:

import requests
wjdata = requests.get('url').json()
print wjdata.get('data').get('current_condition')[0].get('temp_C')

仅针对多个选项…您也可以这样做:

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

#changing username
MYJSON['username'] = 'calixto'
print(MYJSON['username'])

我希望这能有所帮助。

我使用此方法对Json进行深入导航

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]]))
def filter_dict(data: dict, extract):
    try:
        if isinstance(extract, list):
            for i in extract:
                result = filter_dict(data, i)
                if result:
                    return result
        keys = extract.split('.')
        shadow_data = data.copy()
        for key in keys:
            if str(key).isnumeric():
                key = int(key)
            shadow_data = shadow_data[key]
        return shadow_data
    except IndexError:
        return None

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


酷,它现在正在工作。你能解释一下这是为什么吗?亚基已经解释过了@doniyor。这是因为它已使用
json.loads()
转换为dict。你只是想直接访问JSON。。。无需转换为Python可读的内容,也无需使用模块进行转换。最好执行
json.load(urllib2.urlopen('url'))
直接加载,而不是中间保存到内存有没有一种方法可以在不知道索引的情况下返回它,假设有更多的当前条件条目?我得到这个类型错误:每当我尝试使用单词作为数组标记时,列表索引必须是整数,而不是unicode。我怎样才能像你一样工作呢?
请求
是一种处理JSON的奇妙方式。如果你正在处理复杂的URL。。使用它。有没有一种方法可以在不知道索引的情况下返回它,假设有更多的当前条件条目?这是一种聪明的方法,谢谢分享
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]]))
def filter_dict(data: dict, extract):
    try:
        if isinstance(extract, list):
            for i in extract:
                result = filter_dict(data, i)
                if result:
                    return result
        keys = extract.split('.')
        shadow_data = data.copy()
        for key in keys:
            if str(key).isnumeric():
                key = int(key)
            shadow_data = shadow_data[key]
        return shadow_data
    except IndexError:
        return None

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