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

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

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

…变成这样:

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

当前回答

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

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

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

其他回答

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

sudo apt-get update
sudo apt-get install jq

安装jq后,只需使用jq

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

输出看起来像

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

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

sudo apt-get install yajl-tools

然后

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

JSON Ruby Gem与一个shell脚本捆绑在一起,以美化JSON:

sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb

脚本下载:gist.gitub.com/3738968

bat是一个cat克隆,语法突出显示:

例子:

echo '{"bignum":1e1000}' | bat -p -l json

-p将不带头输出,-l将显式指定语言。

它具有JSON的颜色和格式,没有本评论中提到的问题:如何在shell脚本中漂亮地打印JSON?

多亏了J.F.Sebastian非常有用的指导,我想出了一个稍微增强的脚本:

#!/usr/bin/python

"""
Convert JSON data to human-readable form.

Usage:
  prettyJSON.py inputFile [outputFile]
"""

import sys
import simplejson as json


def main(args):
    try:
        if args[1] == '-':
            inputFile = sys.stdin
        else:
            inputFile = open(args[1])
        input = json.load(inputFile)
        inputFile.close()
    except IndexError:
        usage()
        return False
    if len(args) < 3:
        print json.dumps(input, sort_keys = False, indent = 4)
    else:
        outputFile = open(args[2], "w")
        json.dump(input, outputFile, sort_keys = False, indent = 4)
        outputFile.close()
    return True


def usage():
    print __doc__


if __name__ == "__main__":
    sys.exit(not main(sys.argv))