是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
如果您不介意使用第三方工具,您可以直接转到jsonprettyprint.org。这适用于无法在机器上安装软件包的情况。
curl -XPOST https://jsonprettyprint.org/api -d '{"user" : 1}'
其他回答
JSON Ruby Gem与一个shell脚本捆绑在一起,以美化JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
脚本下载:gist.gitub.com/3738968
多亏了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))
我知道最初的帖子要求提供一个shell脚本,但有太多有用和不相关的答案,可能对原作者没有帮助。添加到不相关的内容:)
顺便说一下,我无法使用任何命令行工具。
如果有人想要简单的JSON JavaScript代码,他们可以这样做:
JSON.stringfy(JSON.parse(str), null, 4)
http://www.geospaces.org/geoweb/Wiki.jsp?page=JSON%20Utilities%20Demos
这里是JavaScript代码,它不仅美化了JSON,还按其属性或属性和级别对其进行排序。
如果输入是
{ "c": 1, "a": {"b1": 2, "a1":1 }, "b": 1},
它要么打印(将所有对象分组在一起):
{
"b": 1,
"c": 1,
"a": {
"a1": 1,
"b1": 2
}
}
OR(仅按键排序):
{
"a": {
"a1": 1,
"b1": 2
},
"b": 1,
"c": 1
}
看看Jazor。这是一个用Ruby编写的简单命令行JSON解析器。
gem install jazor
jazor --help
对于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}))}}))"