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

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

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

…变成这样:

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

当前回答

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

其他回答

下面是如何使用Groovy脚本实现这一点。

创建一个Groovy脚本,让我们说“漂亮的打印”

#!/usr/bin/env groovy

import groovy.json.JsonOutput

System.in.withReader { println JsonOutput.prettyPrint(it.readLine()) }

使脚本可执行:

chmod +x pretty-print

现在从命令行开始,

echo '{"foo": "lorem", "bar": "ipsum"}' | ./pretty-print

如果您想在控制台可视化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

输出:

使用Python 2.6+,您可以做到:

echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool

或者,如果JSON在文件中,则可以执行以下操作:

python -m json.tool my_json.json

如果JSON来自互联网源(如API),则可以使用

curl http://my_url/ | python -m json.tool

在所有这些情况下,为了方便起见,您可以使用别名:

alias prettyjson='python -m json.tool'

为了更方便,只需多输入一点即可:

prettyjson_s() {
    echo "$1" | python -m json.tool
}

prettyjson_f() {
    python -m json.tool "$1"
}

prettyjson_w() {
    curl "$1" | python -m json.tool
}

对于所有上述情况。你可以把它放在.bashrc中,它将在shell中随时可用。像prettyjson_s‘{“foo”:“lorem”,“bar”:“ipsum”}‘一样调用它。

请注意,正如@pnd在下面的注释中指出的,在Python 3.5+中,JSON对象在默认情况下不再排序。要排序,请在末尾添加--sort-keys标志。即…|python-mjson.tool——排序键。

我提出了这个解决方案:https://calbertts.medium.com/unix-pipelines-with-curl-requests-and-serverless-functions-e21117ae4c65

# this in your bash profile
jsonprettify() {
  curl -Ss -X POST -H "Content-Type: text/plain" --data-binary @- https://jsonprettify.vercel.app/api/server?indent=$@
}
echo '{"prop": true, "key": [1,2]}' | jsonprettify 4
# {
#     "prop": true,
#     "key": [
#         1,
#         2
#     ]
# }

不需要安装任何东西,如果您安装了internet连接和cURL,则可以使用此功能。

如果您在另一个无法安装任何东西的主机上,这将是该问题的完美解决方案。

我建议使用json::XSperl模块中包含的json_xs命令行实用程序。JSON::XS是一个Perl模块,用于序列化/反序列化JSON,在Debian或Ubuntu机器上可以这样安装:

sudo apt-get install libjson-xs-perl

它显然也可以在CPAN上使用。

要使用它格式化从URL获得的JSON,可以使用curl或wget,如下所示:

$ curl -s http://page.that.serves.json.com/json/ | json_xs

或者:

$ wget -q -O - http://page.that.serves.json.com/json/ | json_xs

要格式化文件中包含的JSON,可以执行以下操作:

$ json_xs < file-full-of.json

要重新格式化为YAML,有些人认为它比JSON更具可读性:

$ json_xs -t yaml < file-full-of.json