Python3获取并解析JSON API
如何使用python解析json api响应? 我目前有:Python3获取并解析JSON API,python,json,python-3.x,api,Python,Json,Python 3.x,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 = re
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对象必须是str,而不是“bytes”
处理json API的python方法是什么?我通常将
请求
包与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]
版本1:(在运行脚本之前执行pip安装请求
)
版本2:(在运行脚本之前执行pip安装wget
)
您可以使用标准库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
使用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())
原始问题中唯一缺少的是对response对象调用
decode
方法(即使这样,也不是每个python3版本)。遗憾的是,没有人指出这一点,每个人都跳上了第三方图书馆
仅使用标准库,对于最简单的用例:
导入json
从urllib.request导入urlopen
def get(url,object_hook=None):
使用urlopen(url)作为资源:#“with”在使用后关闭资源很重要
返回json.load(资源,object\u hook=object\u hook)
简单用例:
data=get('http://url“)#“{”id:1,“$key:13213654}”
打印(数据['id'])#1
打印(数据['$key'])#13213654
或者,如果您愿意,但风险更大:
从类型导入SimpleNamespace
数据=获取('http://url“,lambda o:SimpleNamespace(**o))#”{“id:1,$key:13213654}”
打印(data.id)#1
打印(数据.$key)#无效语法
#虽然你仍然可以
打印(数据._dict_['$key']))
使用请求确实是解决此问题最简单的解决方案。我正在使用Python 3.5,但遇到了一个错误:AttributeError:module'requests'没有属性'get'关于如何解决此问题的任何想法?您可能没有安装它-尝试从命令行运行pip install requests
,我已经尝试过了,但是我得到了一个错误:JSON对象必须是str,而不是“bytes”
。。。知道为什么吗?@pookie试着使用:print(json.loads(r.text)),你可以通过使用:type(r.text)type(r.content)导入请求
和导入json
来检查差异。代码片段应该可以作为复制和粘贴。很好的简洁回答
...
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
import requests
import json
url = 'http://IP-Address:8088/ws/v1/cluster/scheduler'
r = requests.get(url)
data = json.loads(r.content.decode())