目标:将JSON文件合并到一个大文件中
背景:我使用下面的代码来自Issue with merging multiple JSON files in Python
import json
import glob
result = []
for f in glob.glob("/Users/EER/Desktop/JSON_Combo/*.json"):
with open(f, "rb") as infile:
result.append(json.load(infile))
with open("merged_file.json", "wb") as outfile:
json.dump(result, outfile)
但是,我收到以下错误:
JSONDecodeError: Extra data: line 2 column 1 (char 5733)
我检查了Python json.loads shows ValueError: Extra data和JSONDecodeError: Extra data: line 1 column 228 (char 227)和ValueError: Extra Data error when importing json file using python,但他们有点不同。错误的一个潜在原因似乎是我的.json文件是一个字符串列表但我不确定
问题:有关如何解决此错误的任何想法?
您的文件中存在无效的JSON文件,通过使用try except
捕获错误,找出了哪个文件引起了该文件
import json
import glob
result = []
for f in glob.glob("/Users/EER/Desktop/JSON_Combo/*.json"):
with open(f, "rb") as infile:
try:
result.append(json.load(infile))
except ValueError:
print(f)
with open("merged_file.json", "wb") as outfile:
json.dump(result, outfile)