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

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

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

…变成这样:

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

当前回答

你只需要使用jq如果未安装jq,则需要先安装jq。

sudo apt-get update
sudo apt-get install jq

安装jq后,只需使用jq

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

输出看起来像

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

其他回答

在*nix上,从stdin读取和写入stdout效果更好:

#!/usr/bin/env python
"""
Convert JSON data to human-readable form.

(Reads from stdin and writes to stdout)
"""

import sys
try:
    import simplejson as json
except:
    import json

print json.dumps(json.loads(sys.stdin.read()), indent=4)
sys.exit(0)

把这个放在PATH和chmod+x-it中的一个文件(我用AnC的答案命名我的“prettyJSON”)中,就可以开始了。

$ sudo apt-get install edit-json
$ prettify_json myfile.json

当您的系统上安装了节点时,以下工作正常。

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

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

您可以使用Pretier来执行此操作。

npx更漂亮的<JSON文件>应该在给定文件中打印一个经过修饰的JSON版本,而npx更美丽的--write<JSON文件>将用经过修饰的JSON覆盖给定的JSON文件。

我使用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));\
 });\
"