Python 3 获取和解析 JSON API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35120250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:00:38  来源:igfitidea点击:

Python 3 Get and parse JSON API

pythonjsonpython-3.xapi

提问by ClickThisNick

How would I parse a json api response with python? I currently have this:

我将如何用 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))

I'm getting this error: TypeError: the JSON object must be str, not 'bytes'

我收到此错误:TypeError: the JSON object must be str, not 'bytes'

What is the pythonic way to deal with json apis?

处理json apis的pythonic方式是什么?

采纳答案by ferdy

Version 1: (do a pip install requestsbefore running the script)

版本1:(pip install requests在运行脚本之前做一个)

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

Version 2: (do a pip install wgetbefore running the script)

版本 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)

回答by gtlambert

I would usually use the requestspackage with the jsonpackage. The following code should be suitable for your needs:

我通常会使用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))

Output

输出

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

回答by mimin0

you can use standard library python3:

您可以使用标准库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)

output will be like this one:

输出将是这样的:

...
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

回答by kartik

With Python 3

使用 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())

回答by Jacques

The only thing missing in the original question is a call to the decodemethod on the response object (and even then, not for every python3 version). It's a shame no one pointed that out and everyone jumped on a third party library.

原始问题中唯一缺少的是decode对响应对象上的方法的调用(即使如此,也不是针对每个 python3 版本)。很遗憾没有人指出这一点,每个人都跳上了第三方库。

Using only the standard library, for the simplest of use cases :

对于最简单的用例,仅使用标准库:

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)

Simple use case :

简单用例:

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

Or if you prefer, but riskier :

或者,如果您愿意,但风险更大:

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'])