是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
当您的系统上安装了节点时,以下工作正常。
echo '{"test":1,"test2":2}' | npx json
{
"test": 1,
"test2": 2
}
其他回答
我用jshon来做你所描述的事情。只需运行:
echo $COMPACTED_JSON_TEXT | jshon
您还可以传递参数来转换JSON数据。
使用jq工具的原生方式并不太简单。
例如:
cat xxx | jq .
如果您想在控制台可视化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
输出:
对于Perl,使用CPAN模块JSON::XS。它安装一个命令行工具json_xs。
验证:
json_xs -t null < myfile.json
将JSON文件src.JSON前置为pretty.JSON:
< src.json json_xs > pretty.json
如果没有json_x,请尝试json_pp。“pp”代表“纯perl”——该工具仅在perl中实现,没有绑定到外部C库(XS代表perl的“扩展系统”)。
多亏了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))