簡體   English   中英

如何在python中打開json文件

[英]how to open json file in 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)
>>>

根據Python JSON 文檔

如果正在反序列化的數據不是有效的 JSON 文檔,則會引發 JSONDecodeError。

不知道文件的內容,很難說有什么問題,但我懷疑文件中的文本不是有效的 JSON 對象,或者更有可能(根據“額外數據”搜索, 在此處回答)文件“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}
    ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM