You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Python待办事项列表重构为Web服务时遇JSON类型错误求助

解决 TypeError: the JSON object must be str, not 'bytes' 错误

这个问题我之前也碰到过,根源很明确:你用urllib.request.urlopen()拿到响应后,response.read()返回的是字节流(bytes类型),但json.loads()只认字符串,所以就触发了这个类型错误。给你两种简单的解决办法:

方法一:手动解码字节流

在调用json.loads()之前,把字节流解码成UTF-8格式的字符串就行:

修改sample.py里的show_list函数:

@app.route("/")
def show_list():
    with urllib.request.urlopen('http://localhost:6000/api/items') as response:
        resp = response.read().decode('utf-8')  # 新增解码步骤,转成字符串
        resp = json.loads(resp)
    return render_template('index.html', todolist=resp)

方法二:用json.load()直接读取响应对象

更简洁的方式是跳过read()步骤,直接用json.load()读取urlopen返回的响应对象——它会自动帮你处理读取内容和编码转换:

@app.route("/")
def show_list():
    with urllib.request.urlopen('http://localhost:6000/api/items') as response:
        resp = json.load(response)  # 直接加载响应对象,无需手动read和解码
    return render_template('index.html', todolist=resp)

额外小建议

如果之后想简化HTTP请求代码,可以试试requests库,它的API更友好,一行就能完成请求+解析JSON:

# 先安装依赖:pip install requests
import requests

@app.route("/")
def show_list():
    resp = requests.get('http://localhost:6000/api/items').json()
    return render_template('index.html', todolist=resp)

内容的提问来源于stack exchange,提问作者RobbieTheK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:29:16