gpt4 book ai didi

python - 验证和格式化 JSON 文件

转载 作者:IT老高 更新时间:2023-10-28 20:52:20 28 4
gpt4 key购买 nike

我尝试通过 Python 程序运行大约 2000 个 JSON 文件。当 JSON 文件的格式不正确时会出现问题。 (错误:ValueError: No JSON object could be decoded)反过来,我无法将它读入我的程序。

我目前正在做类似以下的事情:

for files in folder:
with open(files) as f:
data = json.load(f); # It causes an error at this part

我知道有离线方法可以验证和格式化 JSON 文件,但有没有一种编程方式来检查和格式化这些文件?如果没有,是否有免费/便宜的替代方法来离线修复所有这些文件,即我只是在包含所有 JSON 文件的文件夹上运行程序并根据需要对其进行格式化?


使用@reece 的评论解决:

invalid_json_files = []
read_json_files = []
def parse():
for files in os.listdir(os.getcwd()):
with open(files) as json_file:
try:
simplejson.load(json_file)
read_json_files.append(files)
except ValueError, e:
print ("JSON object issue: %s") % e
invalid_json_files.append(files)
print invalid_json_files, len(read_json_files)

原来我在我的工作目录中保存了一个不是 JSON 格式的文件,这与我从中读取数据的位置相同。感谢您提供有用的建议。

最佳答案

内置的 JSON 模块可以用作验证器:

import json

def parse(text):
try:
return json.loads(text)
except ValueError as e:
print('invalid json: %s' % e)
return None # or: raise

您可以使用以下方法使其与文件一起使用:

with open(filename) as f:
return json.load(f)

而不是 json.loads,您也可以在错误消息中包含文件名。

在 Python 3.3.5 上,对于 {test: "foo"},我得到:

invalid json: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

在 2.7.6 上:

invalid json: Expecting property name: line 1 column 2 (char 1)

这是因为正确的 json 是 {"test": "foo"}

在处理无效文件时,最好不要进一步处理它们。您可以构建一个 skipped.txt 文件,列出有错误的文件,以便手动检查和修复它们。

如果可能,您应该检查生成无效 json 文件的站点/程序,修复该问题,然后重新生成 json 文件。否则,您将继续拥有无效 JSON 的新文件。

否则,您将需要编写一个自定义 json 解析器来修复常见错误。这样,您应该将原始文件置于源代码控制之下(或存档),以便您可以查看并检查自动化工具修复的差异(作为健全性检查)。模棱两可的情况应该手动解决。

关于python - 验证和格式化 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23344948/

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