提问人: 提问时间:12/9/2008 最后编辑:17 revs, 13 users 24%AnC 更新时间:11/12/2023 访问量:1738964
如何在 shell 脚本中漂亮地打印 JSON?
How can I pretty-print JSON in a shell script?
问:
是否有 (Unix) shell 脚本以人类可读的形式格式化 JSON?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
...变成这样的东西:
{
"foo": "lorem",
"bar": "ipsum"
}
答:
它是 C#,所以也许你可以让它用 Mono 编译,并在 *nix 上工作。对不起,不能保证。
$ 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"
}
更重要的是,你可以在shell中使用python脚本将其作为函数:
json_format(){
python3 -c'import fileinput, json; \
print(json.dumps(json.loads("".join(fileinput.input())), \
sort_keys=True, indent=4, ensure_ascii=False))'
}
然后你可以使用cat json.txt | json_format
评论
to_json
perl -MJSON -nE 'say JSON->new->pretty->encode(from_json $_)' text.json
python -m json.tool
-mjson.tool
的 Python 2.4json.tool
indent
感谢 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))
评论
dict
json.dumps(json.loads('{"b": 1, "a": 2}'), sort_keys=False)
OrderedDict
load
object_pairs_hook=OrderedDict
inputFile = sys.stdin
curl http://somewhere.com/foo.json | pp_json.py
from collections import OrderedDict
com! FormatJSON %!python -c "from collections import OrderedDict; import sys; import json; j = json.load(sys.stdin, object_pairs_hook=OrderedDict); json.dump(j, sys.stdout, sort_keys=False, indent=4, separators=(',', ': '))"
sort_keys = True
J.F. Sebastian 的解决方案在 Ubuntu 8.04 中对我不起作用。
下面是一个修改后的 Perl 版本,适用于较旧的 1.X JSON 库:
perl -0007 -MJSON -ne 'print objToJson(jsonToObj($_, {allow_nonref=>1}), {pretty=>1}), "\n";'
在 *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 的回答之后将我的命名为“prettyJSON”),然后你就可以开始了。chmod +x
评论
或者,使用 Ruby:
echo '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'
评论
to_json
Kernel#jj
echo { "foo": "lorem", "bar": "ipsum" } | ruby -r json -e 'jj JSON.parse gets'
在 Python 2.6+ 或 3 中,您可以使用 json.tool 模块:
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
}
对于上述所有情况。你可以把它放进去,它每次都会在 shell 中可用。像 ..bashrc
prettyjson_s '{"foo": "lorem", "bar": "ipsum"}'
请注意,正如@pnd在下面的评论中指出的那样,在 Python 3.5+ 中,JSON 对象不再默认排序。要进行排序,请在末尾添加 --sort-keys
标志。即.... | python -m json.tool --sort-keys
另一个有用的选项可能是 --no-ensure-ascii
,它禁用非 ASCII 字符的转义(3.9 版中的新功能)。
评论
pygmentize -l javascript
alias pretty='python -mjson.tool | pygmentize -l json
command params | pretty
JSON Ruby Gem 与一个 shell 脚本捆绑在一起,用于美化 JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
评论
json.tool
nesting of 20 is too deep (JSON::NestingError)
sudo apt-get install ruby-json-pure
gem install
prettify_json.rb
~/bin
prettify_json.rb
ppj
chmod +x ppj
curl www.jsonsring.com/something.json | ppj
使用Perl,使用CPAN模块。它安装一个命令行工具。JSON::XS
json_xs
驗證:
json_xs -t null < myfile.json
将 JSON 文件美化为:src.json
pretty.json
< src.json json_xs > pretty.json
如果没有,请尝试 。“pp”代表“纯Perl”——该工具仅在Perl中实现,没有绑定到外部C库(这是XS的缩写,Perl的“扩展系统”)。json_xs
json_pp
评论
-t null
给了我 null:不是有效的 toformat...但是把它关掉,效果很好。谢谢。
我使用 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));\
});\
"
评论
node -p "JSON.stringify(JSON.parse(process.argv[1]), null, '\t');"
看看 Jazor。这是一个用 Ruby 编写的简单命令行 JSON 解析器。
gem install jazor
jazor --help
评论
curl
如果使用 npm 和 Node.js,则可以执行命令,然后通过管道传递命令。做以获得所有选项。它还可以提取特定字段并使用 着色输出。npm install -g json
json
json -h
-i
curl -s http://search.twitter.com/search.json?q=node.js | json
我建议使用 json_xs 命令行实用程序,它包含在 JSON::XS perl 模块中。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
$ sudo apt-get install edit-json
$ prettify_json myfile.json
根据我的经验,yajl
非常好。我使用它的命令将以下行放在我的 :json_reformat
.json
vim
.vimrc
autocmd FileType json setlocal equalprg=json_reformat
我使用 jshon 来完全按照您的描述进行操作。只需运行:
echo $COMPACTED_JSON_TEXT | jshon
还可以传递参数来转换 JSON 数据。
评论
使用 Perl,如果从 CPAN 安装 JSON::P P,您将获得 json_pp 命令。从 B Bycroft 那里窃取示例,你会得到:
[pdurbin@beamish ~]$ echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp
{
"bar" : "ipsum",
"foo" : "lorem"
}
值得一提的是,它预装了 Ubuntu 12.04(至少)和 Debianjson_pp
/usr/bin/json_pp
我通常只做:
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
评论
以下是如何使用 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
评论
jq
我是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
使用 JavaScript/Node.js:看看 vkBeautify.js 插件,它为 JSON 和 XML 文本提供了漂亮的打印。
它是用纯 JavaScript 编写的,小于 1.5 KB(缩小),速度非常快。
我的 JSON 文件没有被这些方法中的任何一个解析。
我的问题类似于帖子 谷歌数据源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/。我认为这个解析器比许多其他解析器更能容错。
评论
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
评论
npx
curl -s "http://api.twitter.com/1/users/show/user.json" | npx jsonlint | less
npm install
我写了一个工具,它有最好的“智能空白”格式化程序之一。与此处的大多数其他选项相比,它产生的可读性更高,输出更冗长。
这就是“智能空白”的样子:
我可能有点偏见,但它是一个很棒的工具,用于从命令行打印和操作 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
这个工具是我目前热衷的项目,所以如果你有任何功能要求,我很有可能会解决它们。
评论
[32m
[33m
[39m
jq
我知道原来的帖子要求一个 shell 脚本,但有太多有用和不相关的答案可能对原作者没有帮助。 增加无关紧要:)
顺便说一句,我无法让任何命令行工具工作。
如果有人想要简单的 JSON JavaScript 代码,他们可以这样做:
JSON.stringfy(JSON.parse(str), null, 4)
http://www.geospaces.org/geoweb/Wiki.jsp?page=JSON%20Utilities%20Demos
下面是 JavaScript 代码,它不仅美化了 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
}
使用以下命令安装 yajl-tools:
sudo apt-get install yajl-tools
然后
echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat
评论
试试 pjson
。它有颜色!
安装它:pip
⚡ pip install pjson
然后将任何 JSON 内容通过管道传递给 .pjson
评论
您可以使用: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"
评论
--sort-keys
curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq '.'
<<<
jq
是最好的,因为它是彩色打印的!
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
评论
echo '{"a":1,"b":2}' | php -r 'echo json_encode(json_decode(fgets(STDIN)), JSON_PRETTY_PRINT)."\n";'
printf '{\n"a":1,\n"b":2\n}' | php -r 'echo json_encode(json_decode(file_get_contents("php://stdin")), JSON_PRETTY_PRINT) . PHP_EOL;'
更新我现在正在按照另一个答案中的建议使用。它在过滤 JSON 方面非常强大,但从根本上讲,它也是一种漂亮的打印 JSON 以供查看的绝佳方式。jq
jsonpp 是一个非常好的命令行 JSON 漂亮的打印机。
从自述文件:
漂亮的打印 Web 服务响应如下:
curl -s -L http://<!---->t.co/tYTq5Pu | jsonpp
并使磁盘上运行的文件变得漂亮:
jsonpp data/long_malformed.json
如果您使用的是 Mac OS X,则可以 .如果没有,您可以简单地将二进制文件复制到 .brew install jsonpp
$PATH
评论
python -mjson.tool
json_pp
jsonpp
这是一个比 Json 的 prettify 命令更好的 Ruby 解决方案。宝石相当不错。colorful_json
gem install colorful_json
echo '{"foo": "lorem", "bar": "ipsum"}' | cjson
{
"foo": "lorem",
"bar": "ipsum"
}
这是 Groovy 的一句话:
echo '{"foo": "lorem", "bar": "ipsum"}' | groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'
如果这是您的选择,您也可以改用在线工具。
我发现 http://jsonprettyprint.net 是最简单和最容易的。
我正在使用 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
}
Pygmentize
我将 Python 的 json.tool 与 pygmentize 相结合:
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g
我的这个答案中列出了一些 pygmentize 的替代方案。
这是一个现场演示:
评论
pygmentize -l json
python-pygments
apt-get install python-pygments
对于 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}))}}))"
gem install jsonpretty
echo '{"foo": "lorem", "bar": "ipsum"}' | jsonpretty
此方法还“检测 HTTP 响应/标头,原封不动地打印它们,然后跳到 正文(用于“curl -i”)”。
一个简单的 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
评论
%*c
printf
c=0; while (c++<offset) printf " "; printf $0;
[]
/^[[{]/
/[]}]/
grep
{ "\"" : "quote" }
{ "\" " : " }
该工具是一个 JSON pretty-printer:ydump
$ ydump my_data.json
{
"foo": "lorem",
"bar": "ipsum"
}
或者,您可以通过管道传入 JSON:
$ echo '{"foo": "lorem", "bar": "ipsum"}' | ydump
{
"foo": "lorem",
"bar": "ipsum"
}
这可能是除了使用该工具之外最短的解决方案。jq
此工具是 OCaml 库的一部分,在此处进行记录。yojson
在 Debian 及其衍生产品上,软件包包含此工具。或者,可以通过OPAM安装。libyojson-ocaml-dev
yojson
只需将输出通过管道传递给 。jq .
例:
twurl -H ads-api.twitter.com '.......' | jq .
评论
cat <file_name.txt> | jq . > <output_name.txt>
brew install jq
如果您使用的是 Mac OS。
jq .
cat file |
jq . <file_name.txt >output_name.txt
<
>
如果您不介意使用第三方工具,您可以简单地卷曲到 jsonprettyprint.org。这适用于无法在计算机上安装软件包的情况。
curl -XPOST https://jsonprettyprint.org/api -d '{"user" : 1}'
评论
echo '{ "foo": "lorem", "bar": "ipsum" }' | curl -XPOST https://jsonprettyprint.org/api -d @-
另外,请务必查看 JSONFUI:支持折叠的命令行 JSON 查看器
如果您安装了 Node.js,则可以使用一行代码自行创建一个。创建一个漂亮的文件:
> vim 漂亮
#!/usr/bin/env node
console.log(JSON.stringify(JSON.parse(process.argv[2]), null, 2));
添加执行权限:
> chmod +x 漂亮
> ./pretty '{“foo”: “lorem”, “bar”: “ipsum”}'
或者,如果您的 JSON 位于文件中:
#!/usr/bin/env node
console.log(JSON.stringify(require("./" + process.argv[2]), null, 2));
> ./漂亮的file.json
评论
我就是这样做的:
curl yourUri | json_pp
它缩短了代码并完成了工作。
评论
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))
使用 jq 工具的原生方式并不太简单。
例如:
cat xxx | jq .
评论
jq . file.json
cat file.json | jq
.
brew install jq
command + | jq
- (示例:
curl localhost:5000/blocks | jq
) - 享受!
在一行中使用 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
jj 速度超快,可以经济地处理巨大的 JSON 文档,不会弄乱有效的 JSON 数字,并且易于使用,例如
jj -p # for reading from STDIN
或
jj -p -i input.json
它(2018 年)仍然很新,所以也许它不会像您期望的那样处理无效的 JSON,但它很容易安装在主要平台上。
您可以使用以下简单命令来实现结果:
echo "{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }"|python -m json.tool
评论
bat
是一个带有语法突出显示的克隆:cat
例:
echo '{"bignum":1e1000}' | bat -p -l json
-p
将输出不带标头,并将显式指定语言。-l
它具有 JSON 的颜色和格式,并且没有以下评论中提到的问题:如何在 shell 脚本中漂亮地打印 JSON?
使用 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 ))"
评论
fs.readFileSync(0)
stdin
JSON.stringify
您可以使用 xidel。
Xidel 是一个命令行工具,用于使用 CSS、XPath 3.0、XQuery 3.0、JSONiq 或模式模板从 HTML/XML 页面或 JSON-API 下载和提取数据。它还可以创建新的或转换的 XML/HTML/JSON 文档。
默认情况下,Xidel pretty-prints:
$ xidel -se '$json' <<< '{"foo":"lorem","bar":"ipsum"}'
{
"foo": "lorem",
"bar": "ipsum"
}
艺术
$ echo '{"foo":"lorem","bar":"ipsum"}' | xidel -se '$json'
{
"foo": "lorem",
"bar": "ipsum"
}
您可以简单地使用 jq 或 json_pp 等标准工具。
echo '{ "foo": "lorem", "bar": "ipsum" }' | json_pp
或
echo '{ "foo": "lorem", "bar": "ipsum" }' | jq
将像下面这样美化输出(jq 甚至更丰富多彩):
{
"foo": "lorem",
"bar": "ipsum"
}
jq 的巨大优势在于,如果您想解析和处理 json,它可以做更多的事情。
评论
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 这一发现的回答!
评论
brew install jq bat tidwall/jj/jj xidel
brew install xidel --head
5s
我想出了这个解决方案:https://calbertts.medium.com/unix-pipelines-with-curl-requests-and-serverless-functions-e21117ae4c65
# 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,则可以使用此功能。
您是否在另一台无法安装任何东西的主机中,这将是该问题的完美解决方案。
当您在系统上安装节点时,以下工作将起作用。
echo '{"test":1,"test2":2}' | npx json
{
"test": 1,
"test2": 2
}
您只需要使用jq
如果没有安装 jq,那么你需要先安装 jq:
sudo apt-get update
sudo apt-get install jq
安装 jq 后,只需要使用:jq
echo '{ "foo": "lorem", "bar": "ipsum" }' | jq
输出如下所示
{
"foo": "lorem",
"bar": "ipsum"
}
评论
brew install jq
如果你想在控制台可视化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
输出:
同意 .您可以将以下函数添加到:jq
$HOME/.bashrc
jqless () {
args=$1
shift
jq --color-output . $args "$@" | less --raw-control-chars
}
这允许任意数量的输入 JSON 文件。
您可以使用 Prettier 来执行此操作。
npx prettier <JSON file>
应该在给定文件中打印 JSON 的美化版本,同时使用美化的 JSON 覆盖给定的 JSON 文件。npx prettier --write <JSON file>
评论
yq 可以用来漂亮地打印 JSON
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json
它有一个定义缩进的选项
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --indent 3
您可以在彩色和单色输出之间进行选择
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --colors
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --no-colors
评论
json