如何在shell脚本中打印JSON?

时间:2020-12-26 21:44:25

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

52 个解决方案

#1


3884  

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 "$1" | python -m json.tool
}

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

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

for all the above cases. You can put this in .bashrc and 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”}'一样调用它。

#2


733  

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结构,包括流。你可以在这里找到他们的教程。

Here is an example:

这是一个例子:

$ jq . <<< '{ "foo": "lorem", "bar": "ipsum" }'
{
  "bar": "ipsum",
  "foo": "lorem"
}

Or in other words:

或者换句话说:

$ echo '{ "foo": "lorem", "bar": "ipsum" }' | jq .
{
  "bar": "ipsum",
  "foo": "lorem"
}

#3


364  

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

我使用JSON.stringify的“space”参数在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 nodejs, specifying json on the command line:

从带有nodejs的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));\
 });\
"

#4


326  

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

This is what "smart whitespace" looks like:

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

如何在shell脚本中打印JSON?

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 |下划线选择'.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.

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

#5


171  

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 curl on the command line using an authentication token:

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

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

#6


84  

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

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

#7


67  

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.json to pretty.json:

将JSON文件src.json整理为pretty.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的“扩展系统”)。

#8


67  

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 +x it, and you're good to go.

把它放在一个文件中(我在AnC的答案之后命名为“prettyJSON”)在你的PATH和chmod + x中,你很高兴。

#9


67  

If you use npm and Node.js, you can do npm install -g json and then pipe the command through json. Do json -h to 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

#10


64  

The JSON Ruby Gem is bundled with a shell script to prettify JSON:

JSON Ruby Gem与shell脚本捆绑在一起来美化JSON:

sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb

Script download: gist.github.com/3738968

脚本下载:gist.github.com/3738968

#11


59  

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

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

For example:

cat xxx | jq .

#12


53  

UPDATE I'm using jq now as suggested in another answer. It's extremely powerful at filtering JSON, but, at its most basic, also an awesome way to pretty print JSON for viewing.

更新我现在正在使用jq,如另一个答案所示。它在过滤JSON方面非常强大,但从最基本的角度来看,它也是一种非常棒的方式来打印JSON以供查看。

jsonpp is a very nice command line JSON pretty printer.

jsonpp是一个非常好的命令行JSON漂亮的打印机。

From the README:

来自README:

Pretty print web service responses like so:

漂亮的打印Web服务响应如下:

curl -s -L http://<!---->t.co/tYTq5Pu | jsonpp

and make beautiful the files running around on your disk:

并使磁盘上运行的文件变得漂亮:

jsonpp data/long_malformed.json

If you're on Mac OS X, you can brew install jsonpp. If not, you can simply copy the binary to somewhere in your $PATH.

如果您使用的是Mac OS X,则可以brew install jsonpp。如果没有,您只需将二进制文件复制到$ PATH中的某个位置即可。

#13


51  

Try pjson. It has colors!

试试pjson。它有颜色!

如何在shell脚本中打印JSON?

Install it with pip:

用pip安装:

⚡ pip install pjson

⚡pipinstall pjson

And then pipe any JSON content to pjson.

然后将任何JSON内容传递给pjson。

#14


41  

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

NOTE: It is not the way to do it.

注意:这不是方法。

The same in Perl:

在Perl中也是如此:

$ cat json.txt \
> | perl -0007 -MJSON -nE'say to_json(from_json($_, {allow_nonref=>1}), 
>                                     {pretty=>1})'
{
   "bar" : "ipsum",
   "foo" : "lorem"
}

Note 2: If you run

注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))'

the nicely readable word becomes \u encoded

可读性很好的单词变成\ u编码

{
    "D\u00fcsseldorf": "lorem", 
    "bar": "ipsum"
}

If the remainder of your pipeline will gracefully handle unicode and you'd like your JSON to also be human-friendly, simply use ensure_ascii=False

如果您的管道的其余部分将优雅地处理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)'

and you'll get:

你会得到:

{
    "Düsseldorf": "lorem", 
    "bar": "ipsum"
}

#15


39  

I use jshon to do exactly what you're describing. Just run:

我使用jshon来完成您所描述的内容。赶紧跑:

echo $COMPACTED_JSON_TEXT | jshon

You can also pass arguments to transform the JSON data.

您还可以传递参数来转换JSON数据。

#16


38  

That's how I do it:

这就是我这样做的方式:

curl yourUri | json_pp

It shortens the code and gets the job done.

它缩短了代码并完成了工作。

#17


37  

Check out Jazor. It's a simple command line JSON parser written in Ruby.

看看Jazor。这是一个用Ruby编写的简单命令行JSON解析器。

gem install jazor
jazor --help

#18


36  

Or, with Ruby:

或者,使用Ruby:

echo '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'

#19


29  

Simply pipe the output to jq ..

只需将输出管道输送到jq ..

Example:

twurl -H ads-api.twitter.com '.......' | jq .

#20


28  

JSONLint has an open-source implementation on github can be used on the command line or included in a node.js project.

JSONLint在github上有一个开源实现,可以在命令行上使用或包含在node.js项目中。

npm install jsonlint -g

and then

jsonlint -p myfile.json

or

curl -s "http://api.twitter.com/1/users/show/user.json" | jsonlint | less

#21


23  

Pygmentize

I combine Python's json.tool with pygmentize:

我将Python的json.tool与pygmentize结合起来:

echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g

There are some alternatives to pygmentize which are listed in my this answer.

pygmentize有一些替代品,我在这个答案中列出了。

Here is a live demo:

这是一个现场演示:

如何在shell脚本中打印JSON?

#22


19  

Vanilla Bash

A simple Bash script (grep/awk) for pretty JSON printing, without third party install:

一个简单的Bash脚本(grep / awk),用于漂亮的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}'

Examples:

1) Read file and pretty print in console

cat file.json | json_pretty.sh

2) Use with the windows GIT Bash from file to file (UTF8 based):

cat fileIn.json |sh.exe json_pretty.sh > fileOut.json

#23


18  

With Perl, if you install JSON::PP from CPAN you'll get the json_pp command. Stealing the example from B Bycroft you get:

使用Perl,如果从CPAN安装JSON :: PP,您将获得json_pp命令。窃取B Bycroft的例子你会得到:

[pdurbin@beamish ~]$ echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp
{
   "bar" : "ipsum",
   "foo" : "lorem"
}

It's worth mentioning that json_pp comes pre-installed with Ubuntu 12.04 (at least) and Debian in /usr/bin/json_pp

值得一提的是,json_pp预先安装了Ubuntu 12.04(至少)和Debian预装在/ usr / bin / json_pp

#24


18  

I recommend using the json_xs command line utility which is included in the JSON::XS perl module. JSON::XS is a Perl module for serializing/deserializing JSON, on a Debian or Ubuntu machine you can install it like this:

我建议使用JSON :: XS perl模块中包含的json_xs命令行实用程序。 JSON :: XS是一个用于序列化/反序列化JSON的Perl模块,在Debian或Ubuntu机器上你可以像这样安装它:

sudo apt-get install libjson-xs-perl

It is obviously also available on CPAN.

它显然也可以在CPAN上使用。

To use it to format JSON obtained from a URL you can use curl or wget like this:

要使用它来格式化从URL获取的JSON,您可以使用curl或wget,如下所示:

$ curl -s http://page.that.serves.json.com/json/ | json_xs

or this:

$ wget -q -O - http://page.that.serves.json.com/json/ | json_xs

and to format JSON contained in a file you can do this:

并格式化文件中包含的JSON,您可以这样做:

$ json_xs < file-full-of.json

To reformat as YAML, which some people consider to be more humanly-readable than JSON:

要重新格式化为YAML,有些人认为它比JSON更具人性化可读性:

$ json_xs -t yaml < file-full-of.json

#25


15  

  1. brew install jq
  2. brew install jq

  3. command + | jq
  4. 命令+ | JQ

  5. (example: curl localhost:5000/blocks | jq)
  6. (例如:curl localhost:5000 / blocks | jq)

  7. Enjoy!

如何在shell脚本中打印JSON?

#26


11  

Install yajl-tools with the command below:

使用以下命令安装yajl-tools:

sudo apt-get install yajl-tools

sudo apt-get install yajl-tools

then,

echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat

echo'{“foo”:“lorem”,“bar”:“ipsum”}'| json_reformat

#27


11  

jj is super-fast, can handle ginormous JSON documents economically, does not mess with valid JSON numbers, and is easy to use, e.g.

jj是超快的,可以经济地处理巨大的JSON文档,不会弄乱有效的JSON数字,并且易于使用,例如

jj -p # for reading from STDIN

or

jj -p -i input.json

It is (2018) still quite new so maybe it won’t handle invalid JSON the way you expect, but it is easy to install on major platforms.

它(2018)仍然很新,所以也许它不会按照你期望的方式处理无效的JSON,但它很容易在主要平台上安装。

#28


10  

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:

根据我的经验,yajl非常好。我使用它的json_reformat命令通过在我的.vimrc中放入以下行来在vim中打印.json文件:

autocmd FileType json setlocal equalprg=json_reformat

#29


9  

The PHP version, if you have PHP >= 5.4.

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

#30


8  

I'm using httpie

我正在使用httpie

$ pip install httpie

And you can use it like this

你可以像这样使用它

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

#1


3884  

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 "$1" | python -m json.tool
}

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

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

for all the above cases. You can put this in .bashrc and 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”}'一样调用它。

#2


733  

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结构,包括流。你可以在这里找到他们的教程。

Here is an example:

这是一个例子:

$ jq . <<< '{ "foo": "lorem", "bar": "ipsum" }'
{
  "bar": "ipsum",
  "foo": "lorem"
}

Or in other words:

或者换句话说:

$ echo '{ "foo": "lorem", "bar": "ipsum" }' | jq .
{
  "bar": "ipsum",
  "foo": "lorem"
}

#3


364  

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

我使用JSON.stringify的“space”参数在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 nodejs, specifying json on the command line:

从带有nodejs的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));\
 });\
"

#4


326  

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

This is what "smart whitespace" looks like:

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

如何在shell脚本中打印JSON?

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 |下划线选择'.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.

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

#5


171  

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 curl on the command line using an authentication token:

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

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

#6


84  

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

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

#7


67  

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.json to pretty.json:

将JSON文件src.json整理为pretty.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的“扩展系统”)。

#8


67  

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 +x it, and you're good to go.

把它放在一个文件中(我在AnC的答案之后命名为“prettyJSON”)在你的PATH和chmod + x中,你很高兴。

#9


67  

If you use npm and Node.js, you can do npm install -g json and then pipe the command through json. Do json -h to 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

#10


64  

The JSON Ruby Gem is bundled with a shell script to prettify JSON:

JSON Ruby Gem与shell脚本捆绑在一起来美化JSON:

sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb

Script download: gist.github.com/3738968

脚本下载:gist.github.com/3738968

#11


59  

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

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

For example:

cat xxx | jq .

#12


53  

UPDATE I'm using jq now as suggested in another answer. It's extremely powerful at filtering JSON, but, at its most basic, also an awesome way to pretty print JSON for viewing.

更新我现在正在使用jq,如另一个答案所示。它在过滤JSON方面非常强大,但从最基本的角度来看,它也是一种非常棒的方式来打印JSON以供查看。

jsonpp is a very nice command line JSON pretty printer.

jsonpp是一个非常好的命令行JSON漂亮的打印机。

From the README:

来自README:

Pretty print web service responses like so:

漂亮的打印Web服务响应如下:

curl -s -L http://<!---->t.co/tYTq5Pu | jsonpp

and make beautiful the files running around on your disk:

并使磁盘上运行的文件变得漂亮:

jsonpp data/long_malformed.json

If you're on Mac OS X, you can brew install jsonpp. If not, you can simply copy the binary to somewhere in your $PATH.

如果您使用的是Mac OS X,则可以brew install jsonpp。如果没有,您只需将二进制文件复制到$ PATH中的某个位置即可。

#13


51  

Try pjson. It has colors!

试试pjson。它有颜色!

如何在shell脚本中打印JSON?

Install it with pip:

用pip安装:

⚡ pip install pjson

⚡pipinstall pjson

And then pipe any JSON content to pjson.

然后将任何JSON内容传递给pjson。

#14


41  

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

NOTE: It is not the way to do it.

注意:这不是方法。

The same in Perl:

在Perl中也是如此:

$ cat json.txt \
> | perl -0007 -MJSON -nE'say to_json(from_json($_, {allow_nonref=>1}), 
>                                     {pretty=>1})'
{
   "bar" : "ipsum",
   "foo" : "lorem"
}

Note 2: If you run

注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))'

the nicely readable word becomes \u encoded

可读性很好的单词变成\ u编码

{
    "D\u00fcsseldorf": "lorem", 
    "bar": "ipsum"
}

If the remainder of your pipeline will gracefully handle unicode and you'd like your JSON to also be human-friendly, simply use ensure_ascii=False

如果您的管道的其余部分将优雅地处理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)'

and you'll get:

你会得到:

{
    "Düsseldorf": "lorem", 
    "bar": "ipsum"
}

#15


39  

I use jshon to do exactly what you're describing. Just run:

我使用jshon来完成您所描述的内容。赶紧跑:

echo $COMPACTED_JSON_TEXT | jshon

You can also pass arguments to transform the JSON data.

您还可以传递参数来转换JSON数据。

#16


38  

That's how I do it:

这就是我这样做的方式:

curl yourUri | json_pp

It shortens the code and gets the job done.

它缩短了代码并完成了工作。

#17


37  

Check out Jazor. It's a simple command line JSON parser written in Ruby.

看看Jazor。这是一个用Ruby编写的简单命令行JSON解析器。

gem install jazor
jazor --help

#18


36  

Or, with Ruby:

或者,使用Ruby:

echo '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'

#19


29  

Simply pipe the output to jq ..

只需将输出管道输送到jq ..

Example:

twurl -H ads-api.twitter.com '.......' | jq .

#20


28  

JSONLint has an open-source implementation on github can be used on the command line or included in a node.js project.

JSONLint在github上有一个开源实现,可以在命令行上使用或包含在node.js项目中。

npm install jsonlint -g

and then

jsonlint -p myfile.json

or

curl -s "http://api.twitter.com/1/users/show/user.json" | jsonlint | less

#21


23  

Pygmentize

I combine Python's json.tool with pygmentize:

我将Python的json.tool与pygmentize结合起来:

echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g

There are some alternatives to pygmentize which are listed in my this answer.

pygmentize有一些替代品,我在这个答案中列出了。

Here is a live demo:

这是一个现场演示:

如何在shell脚本中打印JSON?

#22


19  

Vanilla Bash

A simple Bash script (grep/awk) for pretty JSON printing, without third party install:

一个简单的Bash脚本(grep / awk),用于漂亮的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}'

Examples:

1) Read file and pretty print in console

cat file.json | json_pretty.sh

2) Use with the windows GIT Bash from file to file (UTF8 based):

cat fileIn.json |sh.exe json_pretty.sh > fileOut.json

#23


18  

With Perl, if you install JSON::PP from CPAN you'll get the json_pp command. Stealing the example from B Bycroft you get:

使用Perl,如果从CPAN安装JSON :: PP,您将获得json_pp命令。窃取B Bycroft的例子你会得到:

[pdurbin@beamish ~]$ echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp
{
   "bar" : "ipsum",
   "foo" : "lorem"
}

It's worth mentioning that json_pp comes pre-installed with Ubuntu 12.04 (at least) and Debian in /usr/bin/json_pp

值得一提的是,json_pp预先安装了Ubuntu 12.04(至少)和Debian预装在/ usr / bin / json_pp

#24


18  

I recommend using the json_xs command line utility which is included in the JSON::XS perl module. JSON::XS is a Perl module for serializing/deserializing JSON, on a Debian or Ubuntu machine you can install it like this:

我建议使用JSON :: XS perl模块中包含的json_xs命令行实用程序。 JSON :: XS是一个用于序列化/反序列化JSON的Perl模块,在Debian或Ubuntu机器上你可以像这样安装它:

sudo apt-get install libjson-xs-perl

It is obviously also available on CPAN.

它显然也可以在CPAN上使用。

To use it to format JSON obtained from a URL you can use curl or wget like this:

要使用它来格式化从URL获取的JSON,您可以使用curl或wget,如下所示:

$ curl -s http://page.that.serves.json.com/json/ | json_xs

or this:

$ wget -q -O - http://page.that.serves.json.com/json/ | json_xs

and to format JSON contained in a file you can do this:

并格式化文件中包含的JSON,您可以这样做:

$ json_xs < file-full-of.json

To reformat as YAML, which some people consider to be more humanly-readable than JSON:

要重新格式化为YAML,有些人认为它比JSON更具人性化可读性:

$ json_xs -t yaml < file-full-of.json

#25


15  

  1. brew install jq
  2. brew install jq

  3. command + | jq
  4. 命令+ | JQ

  5. (example: curl localhost:5000/blocks | jq)
  6. (例如:curl localhost:5000 / blocks | jq)

  7. Enjoy!

如何在shell脚本中打印JSON?

#26


11  

Install yajl-tools with the command below:

使用以下命令安装yajl-tools:

sudo apt-get install yajl-tools

sudo apt-get install yajl-tools

then,

echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat

echo'{“foo”:“lorem”,“bar”:“ipsum”}'| json_reformat

#27


11  

jj is super-fast, can handle ginormous JSON documents economically, does not mess with valid JSON numbers, and is easy to use, e.g.

jj是超快的,可以经济地处理巨大的JSON文档,不会弄乱有效的JSON数字,并且易于使用,例如

jj -p # for reading from STDIN

or

jj -p -i input.json

It is (2018) still quite new so maybe it won’t handle invalid JSON the way you expect, but it is easy to install on major platforms.

它(2018)仍然很新,所以也许它不会按照你期望的方式处理无效的JSON,但它很容易在主要平台上安装。

#28


10  

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:

根据我的经验,yajl非常好。我使用它的json_reformat命令通过在我的.vimrc中放入以下行来在vim中打印.json文件:

autocmd FileType json setlocal equalprg=json_reformat

#29


9  

The PHP version, if you have PHP >= 5.4.

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

#30


8  

I'm using httpie

我正在使用httpie

$ pip install httpie

And you can use it like this

你可以像这样使用它

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