是否有(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

其他回答

使用以下命令安装yajl工具:

sudo apt-get install yajl-tools

然后

echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat

尝试pjson。它有颜色!

使用pip安装:

⚡ pip安装pjson

然后将任何JSON内容通过管道传输到pjson。

使

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

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

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

这里是一个现场演示:

我用jshon来做你所描述的事情。只需运行:

echo $COMPACTED_JSON_TEXT | jshon

您还可以传递参数来转换JSON数据。

在一行中使用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