如何解决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
相关产品推荐
相关产品推荐

