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

如何解决TypeError: the JSON object must be str...not TextIOWrapper

报错信息:TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper

报错原因

该报错触发的核心原因是调用json.loads()方法时,传入了已打开的文件对象(TextIOWrapper类型),而json.loads()仅支持接收字符串、字节、字节数组三类输入。

两种可直接使用的解决方案
  • 方案1:使用适配文件对象的json.load()方法直接读取JSON文件,无需额外读取文件内容
import json
# 正确写法示例
with open("你的JSON文件路径.json", "r", encoding="utf-8") as f:
    json_data = json.load(f)
  • 方案2:先读取文件内容为字符串,再传入json.loads()解析
import json
with open("你的JSON文件路径.json", "r", encoding="utf-8") as f:
    # 先读取文件全部内容为字符串
    file_content = f.read()
    json_data = json.loads(file_content)
常见错误写法对照
import json
# 错误写法,直接将文件对象传给json.loads()
with open("你的JSON文件路径.json", "r", encoding="utf-8") as f:
    json_data = json.loads(f) # 此处直接触发对应报错

内容的提问来源于stack exchange,提问作者Md Sydur Rahaman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:18:03