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

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

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

…变成这样:

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

当前回答

我使用JSON.stringify的“space”参数在JavaScript中漂亮地打印JSON。

示例:

// Indent with 4 spaces
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, 4);

// Indent with tabs
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, '\t');

在带有Node.js的Unix命令行中,在命令行中指定JSON:

$ node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\t'));" \
  '{"foo":"lorem","bar":"ipsum"}'

退货:

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

从带有Node.js的Unix命令行,指定包含JSON的文件名,并使用四个空格的缩进:

$ node -e "console.log(JSON.stringify(JSON.parse(require('fs') \
      .readFileSync(process.argv[1])), null, 4));"  filename.json

使用管道:

echo '{"foo": "lorem", "bar": "ipsum"}' | node -e \
"\
 s=process.openStdin();\
 d=[];\
 s.on('data',function(c){\
   d.push(c);\
 });\
 s.on('end',function(){\
   console.log(JSON.stringify(JSON.parse(d.join('')),null,2));\
 });\
"

其他回答

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

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

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

更新我现在使用jq,正如另一个答案中所建议的。它在过滤JSON方面非常强大,但最基本的是,它也是一种漂亮的打印JSON以供查看的绝佳方式。

jsonpp是一个非常好的命令行JSON漂亮的打印机。

从自述文件:

漂亮的打印web服务响应如下:curl-s-L http://<!---->t.co/tYTq5Pu|jsonpp并使磁盘上运行的文件变得漂亮:jsonpp数据/long_malformed.json

如果您使用的是Mac OS X,则可以酝酿安装jsonpp。如果没有,您可以简单地将二进制文件复制到$PATH中的某个位置。

对于Node.js,您也可以使用“util”模块。它使用语法高亮显示、智能缩进、从键中删除引号,并使输出尽可能漂亮。

cat file.json | node -e "process.stdin.pipe(new require('stream').Writable({write: chunk =>  {console.log(require('util').inspect(JSON.parse(chunk), {depth: null, colors: true}))}}))"

看看Jazor。这是一个用Ruby编写的简单命令行JSON解析器。

gem install jazor
jazor --help

我通常只做:

echo '{"test":1,"test2":2}' | python -mjson.tool

要检索选择数据(在本例中为“测试”值):

echo '{"test":1,"test2":2}' | python -c 'import sys,json;data=json.loads(sys.stdin.read()); print data["test"]'

如果JSON数据在文件中:

python -mjson.tool filename.json

如果您想使用身份验证令牌在命令行上使用curl一次性完成所有操作:

curl -X GET -H "Authorization: Token wef4fwef54te4t5teerdfgghrtgdg53" http://testsite/api/ | python -mjson.tool