【问题标题】:Merge JSON files JSONDecodeError合并 JSON 文件 JSONDecodeError
【发布时间】:2018-03-03 17:13:51
【问题描述】:

目标:将 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 dataJSONDecodeError: Extra data: line 1 column 228 (char 227)ValueError: Extra Data error when importing json file using python,但它们有点不同。错误的一个潜在原因似乎是我的 .json 文件是一个字符串列表,但我不确定

问题:关于如何解决此错误的任何想法?

【问题讨论】:

  • 听起来您的文件之一不是有效的 JSON。我建议输入try ... except... 并在except 块中打印文件名,看看哪个是坏的。

标签: python json glob


【解决方案1】:

您的文件中有一个无效的 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)

【讨论】:

  • 我尝试了上面的代码,我得到了以下错误NameError: name 'JSONDecodeError' is not defined
  • 感谢您的更新。我重新运行了代码,现在我得到了以下TypeError: a bytes-like object is required, not 'str'
  • @EER 尝试删除 ValueError 并将其改为 except:
  • 我这样做了。现在我得到TypeError: a bytes-like object is required, not 'str'
  • 好像不太喜欢json.dump(result, outfile)这行代码
猜你喜欢
  • 1970-01-01
  • 2021-11-23
  • 2020-08-06
  • 1970-01-01
  • 2021-02-14
  • 1970-01-01
  • 1970-01-01
  • 2020-02-05
  • 2016-05-18
相关资源
最近更新 更多