Python使用json.load加载JSON文件报JSONDecodeError Extra data错误如何解决
已解决
我尝试通过如下Python代码加载JSON文件:
json_file = open('bill_history.json', "r+") bill_history = json.load(json_file)
但运行时抛出如下异常:
raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 1 column 13 (char 12)
查阅资料得知json.load单行只能读取一个JSON对象,该异常通常在单行存在多个JSON对象时抛出,经确认文件不存在该问题,怀疑是字典嵌套格式有误,需确认JSON文件格式是否有误。
bill_history.json内容如下:
{ "months": [ { "month": "September", "is_paid": "False", "utilities": [ { "utility": "electricity", "is_paid": "False", "bill": "-1", "paid": "0", "resident_payments": [ { "resident": "A", "has_paid": "False", "cost": -1, "paid": 0 }, { "resident": "B", "has_paid": "False", "cost": -1, "paid": 0 }, { "resident": "C", "has_paid": "False", "cost": -1, "paid": 0 }, { "resident": "D", "has_paid": "False", "cost": -1, "paid": 0 }, { "resident": "E", "has_paid": "False", "cost": -1, "paid": 0 }, { "resident": "F", "has_paid": "False", "cost": -1, "paid": 0 } ] } ] } ] }
修复方案
使用json.loads进行加载,代码如下:
json_file = open('bill_history.json', "r+") json_string = json_file.read() bill_history = json.loads(json_string)
内容的提问来源于stack exchange,提问作者softsun2
相关产品推荐
相关产品推荐

