如何在python中打开json文件

2024-05-19 10:27:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我又被困在这里了。。。我有一个名为“data.json”的文件,我想用python打开它,但我遇到了错误

import json
>>> data=json.load(open("data.json"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 340,
in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 4912995)
>>>

Tags: inpyjsondataliblocallineload
2条回答

根据Python JSON documentation

If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.

由于不知道文件的内容,很难说什么是错误的,但我怀疑文件中的文本不是有效的JSON对象,或者更可能(根据“额外数据”搜索,回答here)文件“data.JSON”包含多个JSON对象

例如,使用您的代码: 此文件工作正常

{ "name":"John", "age":30, "car":null }

但是这个

{ "name":"John", "age":30, "car":null }
{ "name":"John", "age":30, "car":null }

抛出相同的错误

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\a\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", 
line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\a\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", 
line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\a\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", 
line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 6 column 1 (char 55)

如果2或超过2 record,您必须reformat您的文件如下所述,或者您必须逐个记录加载文件记录

您需要reformat您的json包含一个array,如下所示:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

相关问题 更多 >

    热门问题