I have around 2000 JSON files which I'm trying to run through a Python program. A problem occurs when a JSON file is not in the correct format. (Error: ValueError: No JSON object could be decoded) In turn, I can't read it into my program.

我目前正在做如下工作:

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

I know there's offline methods to validating and formatting JSON files but is there a programmatic way to check and format these files? If not, is there a free/cheap alternative to fixing all of these files offline i.e. I just run the program on the folder containing all the JSON files and it formats them as required?


使用@Reess的 comments 解决:

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格式的文件,而工作目录正是我读取数据的地方.谢谢你的建议.

推荐答案

The built-in JSON module can be used as a validator:

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,您也可以在错误消息中包含文件名.

On Python 3.3.5, for {test: "foo"}, I get:

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的新文件.

Failing that, you will need to write a custom json parser that fixes common errors. With that, you should be putting the original under source control (or archived), so you can see and check the differences that the automated tool fixes (as a sanity check). Ambiguous cases should be fixed by hand.

Json相关问答推荐

如何在Power BI中集成API和JSON数据后将数据转换为表?

替换字符串中特殊字符的Jolt变换

如何用JQ更改空/布尔/数字的 colored颜色 ?

序列化从/到空值

使用快速json库编写json可以消除所有缩进

在深度嵌套数组中使用布尔属性的jq-select

bash用jq获取第二条JSON记录

如何使用 JOLT 将带有列表的 JSON 项目取消列出为多个项目?

JOLT - 如果对象内部存在键,则将对象移动到数组

使用 BASH 和 JQ 我想将 json 文件与 bash 数组进行比较

判断 JSON 中的对象,而不是条件中提到的对象

使用 Javascript 判断 JSON 对象是否包含值

如何判断 Json 对象中是否存在键并获取其值

如何判断字符串是否为json格式

JSON extract\set 的 SQLite JSON1 示例

json和空数组

有没有办法在 angular.json 中扩展配置?

JSON JQ 如果没有 else

MVC JsonResult camelCase 序列化

使用 jQuery 和 JSON 填充表单?