source

JSON 요소 접근

bestscript 2023. 3. 21. 22:15

JSON 요소 접근

저는 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이 아닌 정수여야 합니다.

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인덱스로 해석할 수 있습니다.

사용하는 대신.read()메모리에 저장하여 읽다json,허락하다json파일에서 직접 로드하려면:

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

요청을 사용하는 대체 솔루션은 다음과 같습니다.

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

'temp_C'는 사전 안에 있는 목록 안에 있는 키입니다.

다음과 같이 동작합니다.

wjson['data']['current_condition'][0]['temp_C']
>> '10'
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]]))

다음과 같이 할 수도 있습니다.

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

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

요구와 함께 get 메서드를 사용하는 다른 방법:

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

다른 답변이 지적했듯이, 이 질문에 대해 받아들여진 답변은 원본 포스터의 데이터 구조 오해를 무시하는 것 같습니다.

주된 문제는 원래 솔루션이 JSON을 순수하게 사전처럼 취급한다는 것입니다. 사실 JSON이...

목록 내, 사전 내, 사전 내

따라서,['data']는 딕셔너리의 최상위 키:값 쌍에 액세스하기 위해 필요합니다.['current_conditions']사전의 다음 레벨에 액세스 합니다.[0]를 사용하여 목록의 첫 번째 요소(1개 요소만 포함)에 액세스해야 합니다.

그래야만 할 수 있다['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리스트를 루프 할 수 있는 엔트리current_conditions) 사용방법:

y = []

for index in range(0,len(x['data']['current_condition']))
   y.append(x['data']['current_condition'][index]['temp_C'])

Json의 자세한 탐색을 위해 이 방법을 수행했습니다.

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

언급URL : https://stackoverflow.com/questions/16129652/accessing-json-elements