是否有(Unix)shell 脚本以人类可读的形式格式化 JSON?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
...变成这样的东西:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell 脚本以人类可读的形式格式化 JSON?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
...变成这样的东西:
{
"foo": "lorem",
"bar": "ipsum"
}
使用 Python 2.6+,您可以:
echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool
或者,如果 JSON 在文件中,您可以执行以下操作:
python -m json.tool my_json.json
如果 JSON 来自 Internet 源(例如 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"}'
.
请注意,正如@pnd 在下面的评论中指出的那样,在 Python 3.5+ 中,JSON 对象默认不再排序。要进行排序,请将--sort-keys
标志添加到末尾。即... | python -m json.tool --sort-keys
。
您可以使用: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"
}
或jq
与身份过滤器一起使用:
$ jq '.foo' <<< '{ "foo": "lorem", "bar": "ipsum" }'
"lorem"
我使用“空格”参数JSON.stringify
在 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));\
});\
"
我编写了一个工具,它拥有最好的“智能空白”格式化程序之一。与此处的大多数其他选项相比,它产生了更具可读性和更少冗长的输出。
这就是“智能空白”的样子:
我可能有点偏见,但它是一个很棒的工具,可以从命令行打印和操作 JSON 数据。它使用起来非常友好,并且有大量的命令行帮助/文档。这是一把瑞士军刀,我用它来完成 1001 种不同的小任务,以任何其他方式执行这些任务都会令人惊讶地烦人。
最新用例:Chrome、开发控制台、网络选项卡,全部导出为 HAR 文件,“cat site.har | underscore select '.url' --outfmt text | grep mydomain”;现在我有一个按时间顺序排列的在加载我公司网站期间进行的所有 URL 提取的列表。
漂亮的打印很容易:
underscore -i data.json print
一样:
cat data.json | underscore print
同样的事情,更明确:
cat data.json | underscore print --outfmt pretty
这个工具是我目前的激情项目,所以如果你有任何功能要求,我很有可能会解决它们。
我通常只是这样做:
echo '{"test":1,"test2":2}' | python -mjson.tool
并检索选择数据(在本例中为“test”的值):
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
感谢 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))
如果你使用 npm 和 Node.js,你可以npm install -g json
通过json
. 做得到json -h
所有的选择。它还可以提取特定字段并使用-i
.
curl -s http://search.twitter.com/search.json?q=node.js | 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_xs
,请尝试json_pp
。“pp”代表“纯 perl”——该工具仅在 Perl 中实现,没有绑定到外部 C 库(这是 XS 的意思,Perl 的“扩展系统”)。
在 *nix 上,从标准输入读取和写入标准输出效果更好:
#!/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的回答之后将我的命名为“prettyJSON” ) chmod +x
,你就可以开始了。
用于漂亮 json 打印的简单 bash 脚本
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
JSON Ruby Gem 捆绑了一个 shell 脚本来美化 JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
脚本下载: gist.github.com/3738968
$ 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"
}
我就是这样做的:
curl yourUri | json_pp
它缩短了代码并完成了工作。
更新我现在正在使用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
.
您可以使用这个简单的命令来实现结果:
echo "{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }"|python -m json.tool
或者,使用 Ruby:
echo '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'
查看Jazor。这是一个用 Ruby 编写的简单命令行 JSON 解析器。
gem install jazor
jazor --help
只需将输出通过管道传输到jq .
.
例子:
twurl -H ads-api.twitter.com '.......' | jq .
您可以简单地使用 jq 或 json_pp 等标准工具。
echo '{ "foo": "lorem", "bar": "ipsum" }' | json_pp
或者
echo '{ "foo": "lorem", "bar": "ipsum" }' | jq
都会像下面这样美化输出(jq 更加丰富多彩):
{
"foo": "lorem",
"bar": "ipsum"
}
jq 的巨大优势在于,如果您想解析和处理 json,它可以做更多事情。
我将 Python 的 json.tool 与 pygmentize 结合起来:
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g
我的这个答案中列出了一些 pygmentize 的替代方法。
这是一个现场演示:
我建议使用 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
jj速度超快,可以经济地处理巨大的 JSON 文档,不会混淆有效的 JSON 数字,并且易于使用,例如
jj -p # for reading from STDIN
或者
jj -p -i input.json
它(2018 年)仍然很新,所以它可能不会像您期望的那样处理无效的 JSON,但它很容易安装在主要平台上。
bat
是一个cat
带有语法高亮的克隆:
例子:
echo '{"bignum":1e1000}' | bat -p -l json
-p
将不带标题输出,-l
并将明确指定语言。
它具有 JSON 的颜色和格式,并且没有此评论中指出的问题:如何在 shell 脚本中漂亮地打印 JSON?
使用以下命令安装 yajl-tools:
sudo apt-get install yajl-tools
然后,
echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat
当您在系统上安装节点时,以下工作。
echo '{"test":1,"test2":2}' | npx json
{
"test": 1,
"test2": 2
}
在一行中使用 Ruby:
echo '{"test":1,"test2":2}' | ruby -e "require 'json'; puts JSON.pretty_generate(JSON.parse(STDIN.read))"
您可以为此设置别名:
alias to_j="ruby -e \"require 'json';puts JSON.pretty_generate(JSON.parse(STDIN.read))\""
然后你可以更方便地使用它
echo '{"test":1,"test2":2}' | to_j
{
"test": 1,
"test2": 2
}
如果你想用颜色显示 JSON,你可以安装awesome_print
,
gem install awesome_print
然后
alias to_j="ruby -e \"require 'json';require 'awesome_print';ap JSON.parse(STDIN.read)\""
试试看!
echo '{"test":1,"test2":2, "arr":["aa","bb","cc"] }' | to_j
使用 Node.js 的单行解决方案如下所示:
$ node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"
例如:
$ cat test.json | node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"
yajl
is very nice, in my experience. I use its json_reformat
command to pretty-print .json
files in vim
by putting the following line in my .vimrc
:
autocmd FileType json setlocal equalprg=json_reformat
这是一个比 Json 的 prettify 命令更好的 Ruby 解决方案。宝石colorful_json
相当不错。
gem install colorful_json
echo '{"foo": "lorem", "bar": "ipsum"}' | cjson
{
"foo": "lorem",
"bar": "ipsum"
}
你只需要使用jq 如果没有安装jq 那么你需要先安装jq。
sudo apt-get update
sudo apt-get install jq
安装好jq之后只需要使用jq
echo '{ "foo": "lorem", "bar": "ipsum" }' | jq
输出看起来像
{
"foo": "lorem",
"bar": "ipsum"
}
PHP 版本,如果您的 PHP >= 5.4。
alias prettify_json=php -E '$o = json_decode($argn); print json_encode($o, JSON_PRETTY_PRINT);'
echo '{"a":1,"b":2}' | prettify_json
JF Sebastian 的解决方案在 Ubuntu 8.04 中对我不起作用。
这是一个修改后的 Perl 版本,可以与旧的 1.X JSON 库一起使用:
perl -0007 -MJSON -ne 'print objToJson(jsonToObj($_, {allow_nonref=>1}), {pretty=>1}), "\n";'
我正在使用httpie
$ pip install httpie
你可以像这样使用它
$ http PUT localhost:8001/api/v1/ports/my
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 93
Content-Type: application/json
Date: Fri, 06 Mar 2015 02:46:41 GMT
Server: nginx/1.4.6 (Ubuntu)
X-Powered-By: HHVM/3.5.1
{
"data": [],
"message": "Failed to manage ports in 'my'. Request body is empty",
"success": false
}
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,Apple 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 发现的回答!
对于 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}))}}))"
该工具ydump
是一个 JSON 漂亮的打印机:
$ ydump my_data.json
{
"foo": "lorem",
"bar": "ipsum"
}
或者您可以通过管道输入 JSON:
$ echo '{"foo": "lorem", "bar": "ipsum"}' | ydump
{
"foo": "lorem",
"bar": "ipsum"
}
除了使用该jq
工具之外,这可能是最短的解决方案。
在 Debian 及其衍生版本中,该软件包libyojson-ocaml-dev
包含此工具。或者,yojson
可以通过OPAM安装。
$ sudo apt-get install edit-json
$ prettify_json myfile.json
If you have Node.js installed you can create one on your own with one line of code. Create a file pretty:
> vim pretty
#!/usr/bin/env node
console.log(JSON.stringify(JSON.parse(process.argv[2]), null, 2));
Add execute permission:
> chmod +x pretty
> ./pretty '{"foo": "lorem", "bar": "ipsum"}'
Or if your JSON is in a file:
#!/usr/bin/env node
console.log(JSON.stringify(require("./" + process.argv[2]), null, 2));
> ./pretty file.json
这是使用Groovy脚本的方法。
创建一个 Groovy 脚本,比如说“pretty-print”
#!/usr/bin/env groovy
import groovy.json.JsonOutput
System.in.withReader { println JsonOutput.prettyPrint(it.readLine()) }
使脚本可执行:
chmod +x pretty-print
现在从命令行,
echo '{"foo": "lorem", "bar": "ipsum"}' | ./pretty-print
# this in your bash profile
jsonprettify() {
curl -Ss -X POST -H "Content-Type: text/plain" --data-binary @- https://jsonprettify.vercel.app/api/server?indent=$@
}
echo '{"prop": true, "key": [1,2]}' | jsonprettify 4
# {
# "prop": true,
# "key": [
# 1,
# 2
# ]
# }
无需安装任何东西,如果您有互联网连接并安装了 cURL,则可以使用此功能。
您是否在无法安装任何东西的另一台主机上,这将是该问题的完美解决方案。
使用 JavaScript/Node.js:看看vkBeautify.js 插件,它为 JSON 和 XML 文本提供了漂亮的打印。
它是用纯 JavaScript 编写的,不到 1.5 KB(缩小)并且速度非常快。
我是json-liner的作者。它是将 JSON 转换为 grep 友好格式的命令行工具。试试看。
$ echo '{"a": 1, "b": 2}' | json-liner
/%a 1
/%b 2
$ echo '["foo", "bar", "baz"]' | json-liner
/@0 foo
/@1 bar
/@2 baz
这是一个 Groovy 单行代码:
echo '{"foo": "lorem", "bar": "ipsum"}' | groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'
gem install jsonpretty
echo '{"foo": "lorem", "bar": "ipsum"}' | jsonpretty
https://github.com/aidanmelen/json_pretty_print
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import json
import jsonschema
def _validate(data):
schema = {"$schema": "http://json-schema.org/draft-04/schema#"}
try:
jsonschema.validate(data, schema,
format_checker=jsonschema.FormatChecker())
except jsonschema.exceptions.ValidationError as ve:
sys.stderr.write("Whoops, the data you provided does not seem to be " \
"valid JSON.\n{}".format(ve))
def pprint(data, python_obj=False, **kwargs):
_validate(data)
kwargs["indent"] = kwargs.get("indent", 4)
pretty_data = json.dumps(data, **kwargs)
if python_obj:
print(pretty_data)
else:
repls = (("u'",'"'),
("'",'"'),
("None",'null'),
("True",'true'),
("False",'false'))
print(reduce(lambda a, kv: a.replace(*kv), repls, pretty_data))
如果你不介意使用第三方工具,你可以简单地curl到jsonprettyprint.org。这是针对您无法在机器上安装软件包的情况。
curl -XPOST https://jsonprettyprint.org/api -d '{"user" : 1}'
我的 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/。我认为这个解析器比许多其他解析器更容错。
您可以使用xidel。
Xidel 是一个命令行工具,用于从 HTML/XML 页面或 JSON-API 下载和提取数据,使用 CSS、XPath 3.0、XQuery 3.0、JSONiq 或模式模板。它还可以创建新的或转换的 XML/HTML/JSON 文档。
Xidel 默认漂亮打印:
$ xidel -se '$json' <<< '{"foo":"lorem","bar":"ipsum"}'
{
"foo": "lorem",
"bar": "ipsum"
}
或者:
$ echo '{"foo":"lorem","bar":"ipsum"}' | xidel -se '$json'
{
"foo": "lorem",
"bar": "ipsum"
}
如果你想在控制台可视化 json 日志,你可以使用 munia-pretty-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
输出:
如果您愿意,您也可以使用在线工具。
我发现http://jsonprettyprint.net是最简单和最容易的。
我知道原始帖子要求提供 shell 脚本,但是有很多有用且不相关的答案可能对原作者没有帮助。添加无关紧要:)
顺便说一句,我无法使用任何命令行工具。
如果有人想要简单的 JSON JavaScript 代码,他们可以这样做:
JSON.stringfy(JSON.parse(str), null, 4)
http://www.geospaces.org/geoweb/Wiki.jsp?page=JSON%20Utilities%20Demos
这里的 JavaScript 代码不仅可以修饰 JSON,还可以按属性或按属性和级别对 JSON 进行排序。
如果输入是
{ "c": 1, "a": {"b1": 2, "a1":1 }, "b": 1},
它要么打印(将所有对象组合在一起):
{
"b": 1,
"c": 1,
"a": {
"a1": 1,
"b1": 2
}
}
或者(只是按键命令):
{
"a": {
"a1": 1,
"b1": 2
},
"b": 1,
"c": 1
}