python-3.x json.decoder.JSONDecodeError:额外数据:第2行第1列(字符190)[重复]

anauzrmj  于 2023-02-06  发布在  Python
关注(0)|答案(3)|浏览(119)
    • 此问题在此处已有答案**:

Python json.loads shows ValueError: Extra data(11个答案)
Loading JSONL file as JSON objects(5个答案)
两年前关闭了。
我在运行下面的代码-

import json

addrsfile = 
open("C:\\Users\file.json", 
"r")
addrJson = json.loads(addrsfile.read())
addrsfile.close()
if addrJson:
    print("yes")

但给我以下错误-

Traceback (most recent call last):
  File "C:/Users/Mayur/Documents/WebPython/Python_WebServices/test.py", line 9, in <module>
    addrJson = json.loads(addrsfile.read())
  File "C:\Users\Mayur\Anaconda3\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Mayur\Anaconda3\lib\json\decoder.py", line 342, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

有人能帮帮我吗?
JSON文件就像-

{"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}
sgtfey8w

sgtfey8w1#

你的json文件中有两条记录,json.loads()不能解码一条以上的记录,你需要一条记录一条记录地解码。
参见Python json.loads shows ValueError: Extra data
或者您需要重新格式化json以包含一个数组:

{
    "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}
    ]
}

将再次被接受。但是不能有多个顶级对象。

2cmtqfgy

2cmtqfgy2#

我正在从REST API调用中解析JSON,遇到了这个错误。原来API变得“更麻烦”了(例如关于参数的顺序等),所以返回了格式错误的结果。检查一下你得到的是你所期望的:)

qxsslcnc

qxsslcnc3#

如果字符串中有json.loads()无法识别的部分,也会出现此错误。在此示例字符串中,将在字符27 (char 27)处引发错误。

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

我的解决方案是使用string.replace()将这些项转换为字符串:

import json

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

string = string.replace("False", '"False"')

dict_list = json.loads(string)

相关问题