查找目录树结构中所有无效的 json 个文件

Find all the json files which are invalid in directory tree structure

我试图在我的目录树中找出无效的 JSON 文件。我有超过 100 个 JSON 文件,所以想看看是否有任何简单的方法可以 运行 一些 linux 命令来找出哪些 JSON 文件无效.我想知道所有这些文件名。

我试过这个命令,但这并没有在我的控制台上给我任何东西,我确实有一堆无效的 JSON 文件。

find . -name \*.json -exec echo {} \; -exec python -m json.tool "{}" \; 2>&1 | grep "No JSON" -B 1

我正在尝试 运行 它在我的 mac 上。

在python你可以做到

#!/usr/bin/env python3

from pathlib import Path
import json

# scan subdirs from current directory
for jsonfile in Path(".").glob("**/*.json"):
    try:
        json.load(open(jsonfile))
        print(jsonfile, "success")
    except Exception as e:
        print(jsonfile, "fail", e)

bashzsh中,使用jq验证JSON个文件:

find . -name "*.json" -print0 | while IFS= read -d '' -r filename; do
    if ! jq . "$filename" >/dev/null 2>&1; then
        echo "$filename is invalid"
    fi
done