Python 3获取和解析JSON API [英] Python 3 Get and parse JSON API
本文介绍了Python 3获取和解析JSON API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将如何使用python解析json api响应? 我目前有这个:
How would I parse a json api response with python? I currently have this:
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"
I'm getting this error: TypeError: the JSON object must be str, not 'bytes'
处理json API的pythonic方法是什么?
What is the pythonic way to deal with json apis?
推荐答案
版本1 :(在运行脚本之前执行pip install requests
)
Version 1: (do a pip install requests
before running the script)
import requests
r = requests.get(url='https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty')
print(r.json())
版本2 :(在运行脚本之前执行pip install wget
)
Version 2: (do a pip install wget
before running the script)
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)
这篇关于Python 3获取和解析JSON API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文