是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
如果您不介意使用第三方工具,您可以直接转到jsonprettyprint.org。这适用于无法在机器上安装软件包的情况。
curl -XPOST https://jsonprettyprint.org/api -d '{"user" : 1}'
其他回答
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
你可以用西德尔。
Xidel是一个命令行工具,可以使用CSS、XPath 3.0、XQuery 3.0、JSONiq或模式模板从HTML/XML页面或JSON API下载和提取数据。它还可以创建新的或转换的XML/HTML/JSON文档。
默认情况下,Xidel漂亮打印:
$ xidel -se '$json' <<< '{"foo":"lorem","bar":"ipsum"}'
{
"foo": "lorem",
"bar": "ipsum"
}
or:
$ echo '{"foo":"lorem","bar":"ipsum"}' | xidel -se '$json'
{
"foo": "lorem",
"bar": "ipsum"
}
使用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——排序键。
如果您不介意使用第三方工具,您可以直接转到jsonprettyprint.org。这适用于无法在机器上安装软件包的情况。
curl -XPOST https://jsonprettyprint.org/api -d '{"user" : 1}'
yq可以用于漂亮地打印JSON
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json
它有一个定义缩进的选项
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --indent 3
您可以选择彩色和单色输出
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --colors
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --no-colors