简体   繁体   English

如何在python中打开json文件

[英]how to open json file in python

I am stuck here again... I have a file named "data.json" and I want to open it with python but I am getting errors.我又被卡在这里了……我有一个名为“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)
>>>

According to Python JSON documentation根据Python JSON 文档

If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.如果正在反序列化的数据不是有效的 JSON 文档,则会引发 JSONDecodeError。

Not knowing the content of your file, it is hard to say what is wrong, but I would suspect that text in your file is not a valid JSON object, or more likely (according to "Extra data" search, answered here ) the file "data.json" includes more than one JSON object.不知道文件的内容,很难说有什么问题,但我怀疑文件中的文本不是有效的 JSON 对象,或者更有可能(根据“额外数据”搜索, 在此处回答)文件“data.json”包含多个 JSON 对象。

For example, using your code: This file works correctly例如,使用您的代码:此文件工作正常

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

but this one但是这个

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

throws the same errors抛出相同的错误

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)

In case 2 or more than 2 record , you have to reformat your file as mentioned below OR you have to load file record by record.如果有2或多于2 record ,您必须按照下面提到的方式reformat文件,或者您必须逐条记录加载文件。

You need to reformat your json to contain an array like below:您需要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}
    ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM