programing

중첩된 JSON 데이터에 액세스하는 Python

kingscode 2023. 3. 12. 12:38
반응형

중첩된 JSON 데이터에 액세스하는 Python

zippopotam.us을 사용하여 특정 도시의 우편번호를 확인하려고 합니다.다음 코드가 동작하고 있습니다.단, 접속을 시도할 때는 제외합니다.post code반환되는 키TypeError: expected string or buffer

r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()

data = json.loads(j)

print j['state']
print data['places']['latitude']

전체 JSON 출력:

{
"country abbreviation": "US",
"places": [
    {
        "place name": "Belmont",
        "longitude": "-71.4594",
        "post code": "02178",
        "latitude": "42.4464"
    },
    {
        "place name": "Belmont",
        "longitude": "-71.2044",
        "post code": "02478",
        "latitude": "42.4128"
    }
],
"country": "United States",
"place name": "Belmont",
"state": "Massachusetts",
"state abbreviation": "MA"
}

장소는 사전이 아닌 목록입니다.따라서 다음 행은 작동하지 않습니다.

print(data['places']['latitude'])

플레이스에 있는 항목 중 하나를 선택한 후 플레이스의 특성을 나열할 수 있습니다.첫 번째 우편번호를 얻으려면 다음 절차를 따릅니다.

print(data['places'][0]['post code'])

첫 번째 네스트 요소가 실제로 배열인지 몰랐습니다.Post Code 키에 대한 올바른 접근 방법은 다음과 같습니다.

r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()

print j['state']
print j['places'][1]['post code']

코드 j는 이미 json data이고 j['places']는 list not dict입니다.

 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = r.json()

 print j['state']
 for each in j['places']:
    print each['latitude']

이 lib를 사용하여 중첩된 dict 키에 액세스합니다.

https://github.com/mewwts/addict

 import requests
 from addict import Dict
 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = Dict(r.json())

 print j.state
 print j.places[1]['post code']  # only work with keys without '-', space, or starting with number 

언급URL : https://stackoverflow.com/questions/23306653/python-accessing-nested-json-data

반응형