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

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

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

…变成这样:

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

当前回答

使

我将Python的json工具与pygmentize相结合:

echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g

我的回答中列出了一些pygmentize的替代方案。

这里是一个现场演示:

其他回答

有TidyJSON。

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

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

在一行中使用Ruby:

echo '{"test":1,"test2":2}' | ruby -e "require 'json'; puts JSON.pretty_generate(JSON.parse(STDIN.read))"

您可以为此设置别名:

alias to_j="ruby -e \"require 'json';puts JSON.pretty_generate(JSON.parse(STDIN.read))\""

然后你可以更方便地使用它

echo '{"test":1,"test2":2}' | to_j

{
  "test": 1,
  "test2": 2
}

如果你想用颜色显示JSON,你可以安装awesome_print,

gem install awesome_print

then

alias to_j="ruby -e \"require 'json';require 'awesome_print';ap JSON.parse(STDIN.read)\""

试试看!

echo '{"test":1,"test2":2, "arr":["aa","bb","cc"] }' | to_j

对于Perl,使用CPAN模块JSON::XS。它安装一个命令行工具json_xs。

验证:

json_xs -t null < myfile.json

将JSON文件src.JSON前置为pretty.JSON:

< src.json json_xs > pretty.json

如果没有json_x,请尝试json_pp。“pp”代表“纯perl”——该工具仅在perl中实现,没有绑定到外部C库(XS代表perl的“扩展系统”)。

同意jq。您可以将以下函数添加到$HOME/.bashrc中:

jqless () {
  args=$1
  shift
  jq --color-output . $args "$@" | less --raw-control-chars
}

这允许任意数量的输入JSON文件。