programing

Python 3 JSON API 가져오기 및 구문 분석

kingscode 2023. 3. 22. 22:45
반응형

Python 3 JSON API 가져오기 및 구문 분석

python으로 json api 응답을 해석하려면 어떻게 해야 하나요?현재 가지고 있는 것은 다음과 같습니다.

import urllib.request
import json

url = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'

def response(url):
    with urllib.request.urlopen(url) as response:
        return response.read()

res = response(url)
print(json.loads(res))

다음 오류가 나타납니다.TypeError: JSON 개체는 'bytes'가 아닌 str이어야 합니다.

Json apis를 다루는 비단뱀식 방법은 무엇입니까?

버전 1: (실행:pip install requests스크립트를 실행하기 전에)

import requests
r = requests.get(url='https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty')
print(r.json())

버전 2: (실행:pip install wget스크립트를 실행하기 전에)

import wget

fs = wget.download(url='https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty')
with open(fs, 'r') as f:
    content = f.read()
print(content)

표준 라이브러리 python3을 사용할 수 있습니다.

import urllib.request
import json
url = 'http://www.reddit.com/r/all/top/.json'
req = urllib.request.Request(url)

##parsing response
r = urllib.request.urlopen(req).read()
cont = json.loads(r.decode('utf-8'))
counter = 0

##parcing json
for item in cont['data']['children']:
    counter += 1
    print("Title:", item['data']['title'], "\nComments:", item['data']['num_comments'])
    print("----")

##print formated
#print (json.dumps(cont, indent=4, sort_keys=True))
print("Number of titles: ", counter)

출력은 다음과 같습니다.

...
Title: Maybe we shouldn't let grandma decide things anymore.  
Comments: 2018
---- 
Title: Carrie Fisher and Her Stunt Double Sunbathing on the Set of Return of The Jedi, 1982  
Comments: 880
---- 
Title: fidget spinner  
Comments: 1537
---- 
Number of titles:  25

저는 보통 이 제품을requests와 함께 포장하다json패키지.고객의 요구에 적합한 코드는 다음과 같습니다.

import requests
import json

url = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'
r = requests.get(url)
print(json.loads(r.content))

산출량

[11008076, 
 11006915, 
 11008202,
 ...., 
 10997668,
 10999859,
 11001695]

첫 번째 질문에서 유일하게 누락된 것은 에 대한 전화입니다.decode메서드(모든 python3 버전이 아님)를 지정합니다.아무도 그것을 지적하지 않고 모두가 제3자 도서관에 뛰어든 것은 유감이다.

가장 간단한 사용 예에서는 표준 라이브러리만 사용합니다.

import json
from urllib.request import urlopen


def get(url, object_hook=None):
    with urlopen(url) as resource:  # 'with' is important to close the resource after use
        return json.load(resource, object_hook=object_hook)

간단한 사용 사례:

data = get('http://url') # '{ "id": 1, "$key": 13213654 }'
print(data['id']) # 1
print(data['$key']) # 13213654

원하신다면, 하지만 리스크가 더 위험합니다.

from types import SimpleNamespace

data = get('http://url', lambda o: SimpleNamespace(**o)) # '{ "id": 1, "$key": 13213654 }'
print(data.id) # 1
print(data.$key) # invalid syntax
# though you can still do
print(data.__dict__['$key'])

Python 3 사용 시

import requests
import json

url = 'http://IP-Address:8088/ws/v1/cluster/scheduler'
r = requests.get(url)
data = json.loads(r.content.decode())

언급URL : https://stackoverflow.com/questions/35120250/python-3-get-and-parse-json-api

반응형