是否有(Unix)Shell脚本以易于理解的格式格式化JSON?
基本上,我希望它可以转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
...变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
#1楼
JSONLint 在GitHub上具有开源实现 ,可以在命令行上使用或包含在Node.js项目中。
npm install jsonlint -g
然后
jsonlint -p myfile.json
要么
curl -s "http://api.twitter.com/1/users/show/user.json" | jsonlint | less
#2楼
我编写了一个工具,该工具具有可用的最佳“智能空白”格式化程序之一。 与此处的大多数其他选项相比,它产生的可读性更高,输出的详细信息更少。
这是“智能空白”的样子:
我可能有点偏颇,但是它是用于从命令行打印和操作JSON数据的强大工具。 它使用起来超级友好,并且具有广泛的命令行帮助/文档。 这是一把瑞士军刀,我用它来完成1001个不同的小任务,这会令人讨厌地以任何其他方式进行。
最新用例:Chrome,Dev控制台,“网络”选项卡,全部导出为HAR文件,“ cat site.har |下划线选择'.url'--outfmt text | grep mydomain”; 现在,我有一个按时间顺序排列的列表,列出了在加载公司网站期间提取的所有URL。
漂亮的打印很容易:
underscore -i data.json print
一样:
cat data.json | underscore print
同样,更明确:
cat data.json | underscore print --outfmt pretty
这个工具是我目前的热情项目,因此,如果您有任何功能要求,我很有可能会解决。
#3楼
在* nix上,从stdin读取并写入stdout的效果更好:
#!/usr/bin/env python
"""
Convert JSON data to human-readable form.
(Reads from stdin and writes to stdout)
"""
import sys
try:
import simplejson as json
except:
import json
print json.dumps(json.loads(sys.stdin.read()), indent=4)
sys.exit(0)
将此文件放入您的PATH文件中(我在AnC的回答后命名为mine“ prettyJSON”),然后对其进行chmod +x
调试 ,您就可以开始了。
#4楼
使用以下命令安装yajl-tools:
sudo apt-get install yajl-tools
然后,
echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat
#5楼
尝试pjson
。 它有颜色!
用pip
安装它:
⚡ pip install pjson
然后将所有JSON内容传递给pjson
。
#6楼
您可以使用: jq
使用非常简单,效果很好! 它可以处理非常大的JSON结构,包括流。 您可以在此处找到他们的教程。
用法示例:
$ jq --color-output . file1.json file1.json | less -R
$ command_with_json_output | jq .
$ jq . # stdin/"interactive" mode, just enter some JSON
$ jq . <<< '{ "foo": "lorem", "bar": "ipsum" }'
{
"bar": "ipsum",
"foo": "lorem"
}
的。 是身份过滤器。
#7楼
或者,使用Ruby:
echo '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'
#8楼
更新我正在使用jq
如另一个答案中所建议。 它在过滤JSON方面非常强大,但是,从最基本的角度来说,它也是一种漂亮地打印JSON以供查看的绝佳方法。
jsonpp是一个非常不错的命令行JSON漂亮打印机。
从自述文件:
漂亮的打印Web服务响应如下:
curl -s -L http://<!---->t.co/tYTq5Pu | jsonpp
使磁盘上到处运行的文件精美:
jsonpp data/long_malformed.json
如果您使用的是Mac OS X,则可以brew install jsonpp
。 如果没有,您可以简单地将二进制文件复制到$PATH
某个位置。
#9楼
使用Python 2.6+,您可以执行以下操作:
echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool
或者,如果JSON在文件中,则可以执行以下操作:
python -m json.tool my_json.json
如果JSON来自互联网来源(例如API),则可以使用
curl http://my_url/ | python -m json.tool
为方便起见,在所有这些情况下都可以使用别名:
alias prettyjson='python -m json.tool'
为了方便起见,请进行更多输入以使其就绪:
prettyjson_s() {
echo "$1" | python -m json.tool
}
prettyjson_f() {
python -m json.tool "$1"
}
prettyjson_w() {
curl "$1" | python -m json.tool
}
对于上述所有情况。 您可以将其放在.bashrc
并且每次在Shell中都可用。 像prettyjson_s '{"foo": "lorem", "bar": "ipsum"}'
一样调用它。
#10楼
JSON Ruby Gem与Shell脚本捆绑在一起以美化JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
脚本下载: gist.github.com/3738968
#11楼
对于Perl,请使用CPAN模块JSON::XS
。 它安装了命令行工具json_xs
。
验证:
json_xs -t null < myfile.json
将JSON文件src.json
为pretty.json
:
< src.json json_xs > pretty.json
如果您没有json_xs
,请尝试json_pp
。 “ pp”表示“纯perl” –该工具仅在Perl中实现,没有绑定到外部C库(XS代表Perl的“扩展系统”)。
#12楼
焦化
我将python的json.tool与pygmentize结合在一起:
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g
我的答案中列出了一些pygmentize的替代方法。
这是一个现场演示:
#13楼
我使用JSON.stringify
的“ space”参数在JavaScript中漂亮地打印JSON。
例子:
// Indent with 4 spaces
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, 4);
// Indent with tabs
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, '\t');
从带有Node.js的Unix命令行中,在命令行上指定JSON:
$ node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\t'));" \
'{"foo":"lorem","bar":"ipsum"}'
返回值:
{
"foo": "lorem",
"bar": "ipsum"
}
从带有Node.js的Unix命令行中,指定包含JSON的文件名,并使用四个空格的缩进:
$ node -e "console.log(JSON.stringify(JSON.parse(require('fs') \
.readFileSync(process.argv[1])), null, 4));" filename.json
使用管道:
echo '{"foo": "lorem", "bar": "ipsum"}' | node -e \
"\
s=process.openStdin();\
d=[];\
s.on('data',function(c){\
d.push(c);\
});\
s.on('end',function(){\
console.log(JSON.stringify(JSON.parse(d.join('')),null,2));\
});\
"
#14楼
$ echo '{ "foo": "lorem", "bar": "ipsum" }' \
> | python -c'import fileinput, json;
> print(json.dumps(json.loads("".join(fileinput.input())),
> sort_keys=True, indent=4))'
{
"bar": "ipsum",
"foo": "lorem"
}
注意:这不是这样做的方法。
在Perl中也是如此:
$ cat json.txt \
> | perl -0007 -MJSON -nE'say to_json(from_json($_, {allow_nonref=>1}),
> {pretty=>1})'
{
"bar" : "ipsum",
"foo" : "lorem"
}
注意2:如果您运行
echo '{ "Düsseldorf": "lorem", "bar": "ipsum" }' \
| python -c'import fileinput, json;
print(json.dumps(json.loads("".join(fileinput.input())),
sort_keys=True, indent=4))'
易读的单词变成\\ u编码
{
"D\u00fcsseldorf": "lorem",
"bar": "ipsum"
}
如果您管道的其余部分将正常处理unicode,并且您希望JSON也对人类友好,则只需使用 ensure_ascii=False
echo '{ "Düsseldorf": "lorem", "bar": "ipsum" }' \
| python -c'import fileinput, json;
print json.dumps(json.loads("".join(fileinput.input())),
sort_keys=True, indent=4, ensure_ascii=False)'
你会得到:
{
"Düsseldorf": "lorem",
"bar": "ipsum"
}
#15楼
感谢JF 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))
#16楼
一个简单的bash脚本,用于漂亮的json打印
json_pretty.sh
#/bin/bash
grep -Eo '"[^"]*" *(: *([0-9]*|"[^"]*")[^{}\["]*|,)?|[^"\]\[\}\{]*|\{|\},?|\[|\],?|[0-9 ]*,?' | awk '{if ($0 ~ /^[}\]]/ ) offset-=4; printf "%*c%s\n", offset, " ", $0; if ($0 ~ /^[{\[]/) offset+=4}'
例:
cat file.json | json_pretty.sh
#17楼
只需将输出传递给jq .
。
例:
twurl -H ads-api.twitter.com '.......' | jq .
#18楼
我就是这样的:
curl yourUri | json_pp
它缩短了代码并完成了工作。
#19楼
使用jq工具的本机方法并不是太简单。
例如:
cat xxx | jq .
#20楼
-
brew install jq
-
command + | jq
- (例如:
curl localhost:5000/blocks | jq
) - 请享用!
#21楼
查看Jazor 。 这是用Ruby编写的简单命令行JSON解析器。
gem install jazor
jazor --help
#22楼
如果使用npm和Node.js,则可以执行npm install -g json
,然后通过json
传递命令。 执行json -h
以获取所有选项。 它还可以提取特定字段,并使用-i
为输出着色。
curl -s http://search.twitter.com/search.json?q=node.js | json
#23楼
我建议使用JSON :: XS perl模块中包含的json_xs命令行实用程序。 JSON :: XS是用于序列化/反序列化JSON的Perl模块,在Debian或Ubuntu计算机上,您可以像这样安装它:
sudo apt-get install libjson-xs-perl
它显然也可以在CPAN上使用 。
要使用它来格式化从URL获得的JSON,可以使用curl或wget,如下所示:
$ curl -s http://page.that.serves.json.com/json/ | json_xs
或这个:
$ wget -q -O - http://page.that.serves.json.com/json/ | json_xs
并格式化文件中包含的JSON,您可以执行以下操作:
$ json_xs < file-full-of.json
要将其重新格式化为YAML ,有些人认为它比JSON更具可读性:
$ json_xs -t yaml < file-full-of.json
#24楼
jj超快,可以经济地处理大量JSON文档,不会与有效的JSON数字混淆,并且易于使用,例如
jj -p # for reading from STDIN
要么
jj -p -i input.json
它(2018)仍然很新,因此也许它不会按照您期望的方式处理无效的JSON,但它很容易在主要平台上安装。
#25楼
您可以使用以下简单命令来获得结果:
echo "{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }"|python -m json.tool
#26楼
bat
是cat
克隆,语法突出显示:
例:
echo '{"bignum":1e1000}' | bat -p -l json
-p
将输出不包含标题的信息, -l
将显式指定语言。
它着色和格式化的JSON, 没有在此评论指出的问题: 在一个shell脚本我怎么能漂亮地打印JSON?
#27楼
您可以简单地使用jq或json_pp之类的标准工具。
echo '{ "foo": "lorem", "bar": "ipsum" }' | json_pp
要么
echo '{ "foo": "lorem", "bar": "ipsum" }' | jq
都会像下面这样美化输出(jq更加丰富多彩):
{
"foo": "lorem",
"bar": "ipsum"
}
jq的巨大优势在于,如果您想解析和处理json,它可以做更多的事情。
#28楼
yajl
我的经验, yajl
非常好。 我用它json_reformat
命令漂亮地打印.json
文件中vim
通过将下面一行在我.vimrc
:
autocmd FileType json setlocal equalprg=json_reformat
#29楼
我使用jshon来做您要描述的事情。 赶紧跑:
echo $COMPACTED_JSON_TEXT | jshon
您还可以传递参数以转换JSON数据。
#30楼
使用Perl,如果您从CPAN安装JSON :: PP ,则将获得json_pp命令。 窃取B Bycroft的示例 ,您会得到:
[pdurbin@beamish ~]$ echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp
{
"bar" : "ipsum",
"foo" : "lorem"
}
值得一提的是json_pp
至少预先安装了Ubuntu 12.04和Debian,位于/usr/bin/json_pp
#31楼
我通常只是这样做:
echo '{"test":1,"test2":2}' | python -mjson.tool
并检索选择的数据(在这种情况下为“测试”的值):
echo '{"test":1,"test2":2}' | python -c 'import sys,json;data=json.loads(sys.stdin.read()); print data["test"]'
如果JSON数据在文件中:
python -mjson.tool filename.json
如果您想使用身份验证令牌在命令行中一次完成curl
全部操作:
curl -X GET -H "Authorization: Token wef4fwef54te4t5teerdfgghrtgdg53" http://testsite/api/ | python -mjson.tool