是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
使
我将Python的json工具与pygmentize相结合:
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g
我的回答中列出了一些pygmentize的替代方案。
这里是一个现场演示:
其他回答
TL;DR:对于性能,请使用jj-p<my.json。
基准
我在这里采取了一些解决方案,并用下一个虚拟脚本对它们进行了基准测试:
function bench {
time (
for i in {1..1000}; do
echo '{ "foo" : { "bar": { "dolorem" : "ipsum", "quia" : { "dolor" : "sit"} } } }' \
| $@ > /dev/null
done
)
}
这是我的mac(32 GB,苹果M1 Max,YMMV)上的结果:
bench python -m json.tool
# 8.39s user 12.31s system 42% cpu 48.536 total
bench jq
# 13.12s user 1.28s system 87% cpu 16.535 total
bench bat -p -l json # NOTE: only syntax colorisation.
# 1.87s user 1.47s system 66% cpu 5.024 total
bench jj -p
# 1.94s user 2.44s system 57% cpu 7.591 total
bench xidel -s - -e '$json' --printed-json-format=pretty
# 4.32s user 1.89s system 76% cpu 8.101 total
感谢@peak和您对jj发现的回答!
JSON Ruby Gem与一个shell脚本捆绑在一起,以美化JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
脚本下载:gist.gitub.com/3738968
我的JSON文件没有被这些方法解析。
我的问题类似于帖子“Google数据源JSON无效吗?”?。
那篇帖子的答案帮助我找到了解决方案。
它被认为是没有字符串键的无效JSON。
{id:'name',label:'Name',type:'string'}
必须是:
{"id": "name", "label": "Name", "type": "string"}
此链接对一些不同的JSON解析器进行了很好的全面比较:http://deron.meranda.us/python/comparing_json_modules/basic
这让我http://deron.meranda.us/python/demjson/.我认为这一个解析器比其他许多解析器更能容错。
下面是Groovy的一行代码:
echo '{"foo": "lorem", "bar": "ipsum"}' | groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'
您可以使用Pretier来执行此操作。
npx更漂亮的<JSON文件>应该在给定文件中打印一个经过修饰的JSON版本,而npx更美丽的--write<JSON文件>将用经过修饰的JSON覆盖给定的JSON文件。