是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
您可以简单地使用jq或json_pp等标准工具。
echo'{“foo”:“lorem”,“bar”:“ipsum”}'| json_pp
or
echo“{”foo“:”lorem“,”bar“:”ipsum“}”| jq
将像下面这样美化输出(jq甚至更丰富多彩):
{
"foo": "lorem",
"bar": "ipsum"
}
jq的巨大优势在于,如果您想解析和处理json,它可以做更多的工作。
其他回答
下面是Groovy的一行代码:
echo '{"foo": "lorem", "bar": "ipsum"}' | groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'
我写了一个工具,它有一个最好的“智能空白”格式器。与这里的大多数其他选项相比,它生成的输出可读性更高,详细程度更低。
下划线cli
这就是“智能空白”的样子:
我可能有点偏见,但它是一个很棒的工具,可以从命令行打印和处理JSON数据。它使用起来超级友好,并且有大量的命令行帮助/文档。这是一把瑞士军刀,我用它来完成1001项不同的小任务,如果用其他方式来做,那会令人惊讶地讨厌。
最新用例:Chrome、开发人员控制台、网络选项卡,全部导出为HAR文件,“cat site.HAR |下划线select‘.url’--outmt text|grep mydomain”;现在,我有一个按时间顺序排列的列表,列出了在加载公司网站期间获取的所有URL。
漂亮的打印很容易:
underscore -i data.json print
同样的事情:
cat data.json | underscore print
同样的事情,更明确:
cat data.json | underscore print --outfmt pretty
这个工具是我目前的激情项目,所以如果你有任何功能需求,我很有机会解决它们。
对于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}))}}))"
如果您想在控制台可视化json日志,可以使用munia漂亮的json
npm install -g munia-pretty-json
您的json数据(app-log.json)
{"time":"2021-06-09T02:50:22Z","level":"info","message":"Log for pretty JSON","module":"init","hostip":"192.168.0.138","pid":123}
{"time":"2021-06-09T03:27:43Z","level":"warn","message":"Here is warning message","module":"send-message","hostip":"192.168.0.138","pid":123}
运行命令:
munia-pretty-json app-log.json
下面是控制台上的可读输出:
您可以使用模板格式化输出。默认模板为“{time}{level-c}{{message}”
使用模板:
munia-pretty-json -t '{module -c} - {level} - {message}' app-log.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))