如何用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'

处理jsonAPI的Python方式是什么?

推荐答案

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

Json相关问答推荐

从JSON格式提取数据时分隔通用名称

服务器不返回JSON

如何将加权边列表导出到JSON树?

使用Jolt v.0.1.1向每个json元素添加一个键-值对

Vega-Lite(Deneb):难以将最小和最大值应用于折线图和文本标签以及线条末尾的点

Android 如何判断小时时间是否在两个时间之间?

如何使用jolt规范将一个对象添加到另一个对象中并删除该对象

如何将复杂的 JSON 反序列化为 Rust 类型?

从 JSON 响应中获取最新版本发布字段

将文本转换为 python 列表

如何将动态复杂 json 解析为dart 对象或模型

将哈希表转换为 json 后,Powershell 缺少数组

缺少所需的请求正文内容:org.springframework.web.method.HandlerMethod$HandlerMethodParameter

以 JSON 格式访问(新型、公共)Google 工作表

如何比较 JSON 文档并返回与 Jackson 或 Gson 的差异?

在 JSON 反序列化期间没有为System.String类型定义无参数构造函数

关于使用 $ref 的 JSON 模式

[__NSCFNumber 长度]:发送到实例 UITableView 的无法识别的 Select 器

JSON JQ 如果没有 else

Protocol Buffer vs Json - 何时 Select 一个而不是另一个