Wie würde ich eine Json-API-Antwort mit Python analysieren? Ich habe derzeit Folgendes:
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))
Ich erhalte folgende Fehlermeldung: TypeError: Das JSON-Objekt muss str sein und nicht 'bytes'
Was ist der pythonische Weg, mit Json Apis umzugehen?
Version 1: (Vor dem Importieren des Moduls eine Pip-Installationsanforderung durchführen)
import requests
r = requests.get(url='https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty')
print(r.json())
Version 2: (Vor dem Importieren des Moduls eine Pip-Installation durchführen)
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)
sie können die Standardbibliothek python3 verwenden:
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)
ausgabe wird wie folgt sein:
...
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
Ich würde normalerweise das Paket requests
mit dem Paket json
verwenden. Der folgende Code sollte für Ihre Bedürfnisse geeignet sein:
import requests
import json
url = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'
r = requests.get(url)
print(json.loads(r.content))
Ausgabe
[11008076,
11006915,
11008202,
....,
10997668,
10999859,
11001695]
Mit 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())
Das einzige, was in der ursprünglichen Frage fehlt, ist ein Aufruf der decode
-Methode für das Antwortobjekt (und selbst dann nicht für jede Python3-Version). Es ist eine Schande, dass niemand darauf hingewiesen hat und jeder auf eine Drittanbieter-Bibliothek zugegriffen hat.
Verwenden Sie für die einfachsten Anwendungsfälle nur die Standardbibliothek:
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)
Einfacher Anwendungsfall:
data = get('http://url') # '{ "id": 1, "$key": 13213654 }'
print(data['id']) # 1
print(data['$key']) # 13213654
Oder wenn Sie es vorziehen, aber riskanter:
from types import SimpleNamespace
data = get('http://url', lamda o: SimpleNamespace(**o)) # '{ "id": 1, "$key": 13213654 }'
print(data.id) # 1
print(data.$key) # invalid syntax