是否有(Unix)shell脚本将JSON格式化为可读格式?

基本上,我希望它转换以下内容:

{ "foo": "lorem", "bar": "ipsum" }

…变成这样:

{
    "foo": "lorem",
    "bar": "ipsum"
}

当前回答

$ echo '{ "foo": "lorem", "bar": "ipsum" }' \
> | python -c'import fileinput, json;
> print(json.dumps(json.loads("".join(fileinput.input())),
>                  sort_keys=True, indent=4))'
{
    "bar": "ipsum",
    "foo": "lorem"
}

注意:不是这样做的。

在Perl中也是如此:

$ cat json.txt \
> | perl -0007 -MJSON -nE'say to_json(from_json($_, {allow_nonref=>1}), 
>                                     {pretty=>1})'
{
   "bar" : "ipsum",
   "foo" : "lorem"
}

注2:如果你跑步

echo '{ "Düsseldorf": "lorem", "bar": "ipsum" }' \
| python -c'import fileinput, json;
print(json.dumps(json.loads("".join(fileinput.input())),
                 sort_keys=True, indent=4))'

可读性很好的单词将被编码

{
    "D\u00fcsseldorf": "lorem", 
    "bar": "ipsum"
}

如果您的管道的其余部分将优雅地处理unicode,并且您希望JSON也是人性化的,那么只需使用ensure_ascii=False

echo '{ "Düsseldorf": "lorem", "bar": "ipsum" }' \
| python -c'import fileinput, json;
print json.dumps(json.loads("".join(fileinput.input())),
                 sort_keys=True, indent=4, ensure_ascii=False)'

你会得到:

{
    "Düsseldorf": "lorem", 
    "bar": "ipsum"
}

其他回答

您可以使用:jq

它的使用非常简单,而且效果很好!它可以处理非常大的JSON结构,包括流。你可以找到他们的教程。

用法示例:

$ jq --color-output . file1.json file1.json | less -R

$ command_with_json_output | jq .

$ jq # stdin/"interactive" mode, just enter some JSON

$ jq <<< '{ "foo": "lorem", "bar": "ipsum" }'
{
  "bar": "ipsum",
  "foo": "lorem"
}

或者将jq与身份过滤器一起使用:

$ jq '.foo' <<< '{ "foo": "lorem", "bar": "ipsum" }'
"lorem"

有TidyJSON。

它是C#,所以也许你可以让它用Mono编译,并使用*nix。但没有保证,抱歉。

我的JSON文件没有被这些方法解析。

我的问题类似于帖子“Google数据源JSON无效吗?”?。

那篇帖子的答案帮助我找到了解决方案。

它被认为是没有字符串键的无效JSON。

{id:'name',label:'Name',type:'string'}

必须是:

{"id": "name", "label": "Name", "type": "string"}

此链接对一些不同的JSON解析器进行了很好的全面比较:http://deron.meranda.us/python/comparing_json_modules/basic

这让我http://deron.meranda.us/python/demjson/.我认为这一个解析器比其他许多解析器更能容错。

如果您想在控制台可视化json日志,可以使用munia漂亮的json

npm install -g munia-pretty-json

您的json数据(app-log.json)

{"time":"2021-06-09T02:50:22Z","level":"info","message":"Log for pretty JSON","module":"init","hostip":"192.168.0.138","pid":123}
{"time":"2021-06-09T03:27:43Z","level":"warn","message":"Here is warning message","module":"send-message","hostip":"192.168.0.138","pid":123}

运行命令:

munia-pretty-json app-log.json

下面是控制台上的可读输出:

您可以使用模板格式化输出。默认模板为“{time}{level-c}{{message}”

使用模板:

munia-pretty-json -t '{module -c} - {level} - {message}' app-log.json

输出:

JSONLint在GitHub上有一个开源实现,可以在命令行上使用,也可以包含在Node.js项目中。

npm install jsonlint -g

然后

jsonlint -p myfile.json

or

curl -s "http://api.twitter.com/1/users/show/user.json" | jsonlint | less