gpt4 book ai didi

python - 在 python 中解析 json 文件会造成困难

转载 作者:太空宇宙 更新时间:2023-11-04 09:30:53 25 4
gpt4 key购买 nike

我想用 python 解析一个 json 文件。我不知道文件的内容。我从网站上以 json 格式下载了这个文件。

据我所知,要解析一个 json 文件,我们需要这段代码

import json

sourcefile=open("News_Category_Dataset_v2.json","r")
json_data=json.load(sourcefile)

print (json_data)

但是我遇到了如下所述的错误。 jsonparse.py 是我的文件名,保存在我的电脑 d:/algorithm

D:\python\envs\algorithms\python.exe D:/algorithms/jsonparse.py追溯(最近一次通话最后一次):

File "D:/algorithms/jsonparse.py", line 4, in <module>
json_data=json.load(sourcefile)

File "D:\python\envs\algorithms\lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

File "D:\python\envs\algorithms\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)

File "D:\python\envs\algorithms\lib\json\decoder.py", line 342, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 366)

Process finished with exit code 1

我该如何解决这个问题?

最佳答案

您的文件不是 json。但其中每一行都是 json。

这段代码应该对你有帮助

import json

json_list = []
for i in open('test.json'):
json_line = json.loads(i)
json_list.append(json_line)
print(json_list)

关于python - 在 python 中解析 json 文件会造成困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55822374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com