如何在 shell 脚本中漂亮地打印 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/352098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:09:37  来源:igfitidea点击:

How can I pretty-print JSON in a shell script?

jsonunixcommand-lineformatpretty-print

提问by B Bycroft

Is there a (Unix) shell script to format JSON in human-readable form?

是否有(Unix)shell 脚本以人类可读的形式格式化 JSON?

Basically, I want it to transform the following:

基本上,我希望它转换以下内容:

{ "foo": "lorem", "bar": "ipsum" }

... into something like this:

...变成这样:

{
    "foo": "lorem",
    "bar": "ipsum"
}

回答by B Bycroft

With Python 2.6+ you can just do:

使用 Python 2.6+ 你可以这样做:

echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool

or, if the JSON is in a file, you can do:

或者,如果 JSON 在文件中,您可以执行以下操作:

python -m json.tool my_json.json

if the JSON is from an internet source such as an API, you can use

如果 JSON 来自互联网资源,例如 API,则可以使用

curl http://my_url/ | python -m json.tool

For convenience in all of these cases you can make an alias:

为了方便所有这些情况,您可以创建别名:

alias prettyjson='python -m json.tool'


For even more convenience with a bit more typing to get it ready:

为了更方便,只需输入更多内容即可准备就绪:

prettyjson_s() {
    echo "" | python -m json.tool
}

prettyjson_f() {
    python -m json.tool ""
}

prettyjson_w() {
    curl "" | python -m json.tool
}

for all the above cases. You can put this in .bashrcand it will be available every time in shell. Invoke it like prettyjson_s '{"foo": "lorem", "bar": "ipsum"}'.

对于上述所有情况。你可以把.bashrc它放进去,它每次在 shell 中都可用。像prettyjson_s '{"foo": "lorem", "bar": "ipsum"}'.

回答by Vita Pluvia

You can use: jq

您可以使用: jq

It's very simple to use and it works great! It can handle very large JSON structures, including streams. You can find their tutorials here.

它使用起来非常简单,而且效果很好!它可以处理非常大的 JSON 结构,包括流。您可以在此处找到他们的教程。

Usage examples:

用法示例:

$ 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"
}

The . is the identity filter.

这 。是身份过滤器。

回答by Somu

I use the "space" argument of JSON.stringifyto pretty-print JSON in JavaScript.

我使用“space”参数JSON.stringify在 JavaScript 中漂亮地打印 JSON。

Examples:

例子:

// Indent with 4 spaces
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, 4);

// Indent with tabs
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, '\t');

From the Unix command-line with Node.js, specifying JSON on the command line:

从带有 Node.js 的 Unix 命令行,在命令行上指定 JSON:

$ node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\t'));" \
  '{"foo":"lorem","bar":"ipsum"}'

Returns:

返回:

{
    "foo": "lorem",
    "bar": "ipsum"
}

From the Unix command-line with Node.js, specifying a filename that contains JSON, and using an indent of four spaces:

从带有 Node.js 的 Unix 命令行,指定一个包含 JSON 的文件名,并使用四个空格的缩进:

$ node -e "console.log(JSON.stringify(JSON.parse(require('fs') \
      .readFileSync(process.argv[1])), null, 4));"  filename.json

Using a pipe:

使用管道:

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));\
 });\
"

回答by Dave Dopson

I wrote a tool that has one of the best "smart whitespace" formatters available. It produces more readable and less verbose output than most of the other options here.

我写了一个工具,它拥有最好的“智能空白”格式化程序之一。与此处的大多数其他选项相比,它会产生更具可读性和更少冗长的输出。

underscore-cli

下划线-cli

This is what "smart whitespace" looks like:

这就是“智能空白”的样子:

I may be a bit biased, but it's an awesome tool for printing and manipulating JSON data from the command-line. It's super-friendly to use and has extensive command-line help/documentation. It's a Swiss Army knife that I use for 1001 different small tasks that would be surprisingly annoying to do any other way.

我可能有点偏见,但它是一个很棒的工具,用于从命令行打印和操作 JSON 数据。它使用起来非常友好,并且有大量的命令行帮助/文档。这是一把瑞士军刀,我用它来完成 1001 种不同的小任务,如果用其他方式做这些小任务都会令人惊讶。

Latest use-case: Chrome, Dev console, Network tab, export all as HAR file, "cat site.har | underscore select '.url' --outfmt text | grep mydomain"; now I have a chronologically ordered list of all URL fetches made during the loading of my company's site.

最新用例:Chrome、开发控制台、网络选项卡,全部导出为 HAR 文件,“cat site.har | underscore select '.url' --outfmt text | grep mydomain”;现在我有一个按时间顺序排列的列表,其中包含在加载我公司网站期间进行的所有 URL 提取。

Pretty printing is easy:

漂亮的印刷很容易:

underscore -i data.json print

Same thing:

一样:

cat data.json | underscore print

Same thing, more explicit:

同样的事情,更明确:

cat data.json | underscore print --outfmt pretty

This tool is my current passion project, so if you have any feature requests, there is a good chance I'll address them.

这个工具是我目前的激情项目,所以如果你有任何功能要求,我很有可能会解决它们。

回答by locojay

I usually just do:

我通常只是这样做:

echo '{"test":1,"test2":2}' | python -mjson.tool

And to retrieve select data (in this case, "test"'s value):

并检索选择数据(在这种情况下,“测试”的值):

echo '{"test":1,"test2":2}' | python -c 'import sys,json;data=json.loads(sys.stdin.read()); print data["test"]'

If the JSON data is in a file:

如果 JSON 数据在文件中:

python -mjson.tool filename.json

If you want to do it all in one go with curlon the command line using an authentication token:

如果您想curl在命令行上使用身份验证令牌一次性完成所有操作:

curl -X GET -H "Authorization: Token wef4fwef54te4t5teerdfgghrtgdg53" http://testsite/api/ | python -mjson.tool

回答by locojay

Thanks to J.F. Sebastian's very helpful pointers, here's a slightly enhanced script I've come up with:

感谢 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))

回答by isaacs

If you use npm and Node.js, you can do npm install -g jsonand then pipe the command through json. Do json -hto get all the options. It can also pull out specific fields and colorize the output with -i.

如果您使用 npm 和 Node.js,您可以先执行npm install -g json,然后通过json. 做json -h以获得所有选项。它还可以提取特定字段并使用-i.

curl -s http://search.twitter.com/search.json?q=node.js | json

回答by Olexandr Minzak

It is not too simple with a native way with the jq tools.

使用jq 工具的本机方式并不太简单。

For example:

例如:

cat xxx | jq .

回答by knb

With Perl, use the CPAN module JSON::XS. It installs a command line tool json_xs.

对于 Perl,使用 CPAN 模块JSON::XS。它安装了一个命令行工具json_xs

Validate:

证实:

json_xs -t null < myfile.json

Prettify the JSON file src.jsonto pretty.json:

将 JSON 文件美化src.jsonpretty.json

< src.json json_xs > pretty.json

If you don't have json_xs, try json_pp. "pp" is for "pure perl" – the tool is implemented in Perl only, without a binding to an external C library (which is what XS stands for, Perl's "Extension System").

如果没有json_xs,请尝试json_pp。“pp”代表“纯 perl”——该工具仅在 Perl 中实现,没有绑定到外部 C 库(XS 代表 Perl 的“扩展系统”)。

回答by Daryl Spitzer

On *nix, reading from stdin and writing to stdout works better:

在 *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)

Put this in a file (I named mine "prettyJSON" after AnC's answer) in your PATH and chmod +xit, and you're good to go.

把它放在你的 PATH 和它的文件中(我在AnC的回答之后将我的命名为“prettyJSON” )chmod +x,然后你就可以开始了。