如何在一个(Unix) shell脚本中打印JSON ?

时间:2022-02-11 01:59:40

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

49 个解决方案

#1


3622  

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来自internet源,比如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


650  

You can use: 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


350  

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

我使用[JSON]的“空间”参数。1在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:

从Unix命令行到节点。js,指定包含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


321  

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

underscore-cli

This is what "smart whitespace" looks like:

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

如何在一个(Unix) 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, Dev控制台,网络标签,导出所有的哈尔文件,“猫网站。哈|下划线。url'——outfmt文本| 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


163  

I usually just do:

我通常只做:

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

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

并检索select数据(在本例中为“test”的值):

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


82  

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


64  

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


63  

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

在*nix上,从stdin和writing到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.

在你的路径和chmod +x中,把这个放在一个文件中(我命名为“prettyJSON”),然后你就可以走了。

#9


62  

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

#10


62  

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和节点。您可以在npm中安装-g json,然后通过json导入命令。使用json -h获得所有选项。它还可以提取特定的字段并将输出与-i混合。

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

#11


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:

的自述:

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上,你可以酝酿安装jsonpp。如果不是,您可以简单地将二进制文件复制到$PATH中的某个地方。

#12


50  

Try pjson. It has colors!

pjson试试。它有色彩!

如何在一个(Unix) shell脚本中打印JSON ?

Install it with pip:

pip安装:

⚡ pip install pjson

⚡pip安装pjson

And then pipe any JSON content to pjson.

然后将任何JSON内容导入到pjson中。

#13


45  

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

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

For example:

例如:

cat xxx | jq .

#14


38  

$ 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


38  

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


35  

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

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

gem install jazor
jazor --help

#17


32  

Or, with Ruby:

或者,使用Ruby:

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

#18


29  

Simply pipe the output to jq ..

简单地将输出输出到jq ..

Example:

例子:

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

#19


27  

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

JSONLint在github上有一个开源实现,可以在命令行上使用,也可以在节点中使用。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

#20


25  

That's how I do it:

我就是这么做的:

curl yourUri | json_pp

It shortens the code and gets the job done.

它缩短了代码并完成了任务。

#21


19  

Pygmentize

I combine Python's json.tool with pygmentize:

我把Python的json。与pygmentize工具:

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

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

在我的这个答案中,有一些关于pygze的替代方法。

Here is a live demo:

这里有一个现场演示:

如何在一个(Unix) shell脚本中打印JSON ?

#22


17  

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中包含的json_xs命令行实用程序::XS perl模块。XS是一个Perl模块,用于序列化/反序列化JSON,在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

#23


15  

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,如果您安装了JSON::来自CPAN的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


14  

  1. brew install jq
  2. 酿造安装金桥
  3. command + | jq
  4. 命令+ |金桥
  5. (example: curl localhost:5000/blocks | jq)
  6. (示例:curl localhost:5000/block | jq)
  7. Enjoy!
  8. 享受吧!

如何在一个(Unix) shell脚本中打印JSON ?

#25


11  

Install yajl-tools with the command below:

使用以下命令安装yajl工具:

sudo apt-get install yajl-tools

sudo apt-get安装yajl-tools

then,

然后,

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

echo ' {“foo”:“lorem”,“酒吧”:“添加”}”| json_reformat

#26


8  

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命令在vim中使用下面的行来在vim中打印.json文件。

autocmd FileType json setlocal equalprg=json_reformat

#27


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
 }

#28


8  

Vanilla Bash

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

一个简单的Bash脚本(grep/awk),用于漂亮的JSON打印,无需第三方安装:

json_pretty.sh

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

#29


7  

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


7  

I know this question has been replied ad nauseam, but I wanted to document a Ruby solution that is better than Json's prettify command, the gem colorful_json is fairly good.

我知道这个问题已经令人厌恶了,但是我想要记录一个比Json更好的Ruby解决方案,gem colorful_json是相当不错的。

gem install colorful_json
echo '{"foo": "lorem", "bar": "ipsum"}' | cjson
{
  "foo": "lorem",
  "bar": "ipsum"
}

#1


3622  

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来自internet源,比如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


650  

You can use: 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


350  

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

我使用[JSON]的“空间”参数。1在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:

从Unix命令行到节点。js,指定包含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


321  

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

underscore-cli

This is what "smart whitespace" looks like:

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

如何在一个(Unix) 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, Dev控制台,网络标签,导出所有的哈尔文件,“猫网站。哈|下划线。url'——outfmt文本| 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


163  

I usually just do:

我通常只做:

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

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

并检索select数据(在本例中为“test”的值):

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


82  

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


64  

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


63  

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

在*nix上,从stdin和writing到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.

在你的路径和chmod +x中,把这个放在一个文件中(我命名为“prettyJSON”),然后你就可以走了。

#9


62  

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

#10


62  

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和节点。您可以在npm中安装-g json,然后通过json导入命令。使用json -h获得所有选项。它还可以提取特定的字段并将输出与-i混合。

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

#11


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:

的自述:

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上,你可以酝酿安装jsonpp。如果不是,您可以简单地将二进制文件复制到$PATH中的某个地方。

#12


50  

Try pjson. It has colors!

pjson试试。它有色彩!

如何在一个(Unix) shell脚本中打印JSON ?

Install it with pip:

pip安装:

⚡ pip install pjson

⚡pip安装pjson

And then pipe any JSON content to pjson.

然后将任何JSON内容导入到pjson中。

#13


45  

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

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

For example:

例如:

cat xxx | jq .

#14


38  

$ 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


38  

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


35  

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

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

gem install jazor
jazor --help

#17


32  

Or, with Ruby:

或者,使用Ruby:

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

#18


29  

Simply pipe the output to jq ..

简单地将输出输出到jq ..

Example:

例子:

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

#19


27  

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

JSONLint在github上有一个开源实现,可以在命令行上使用,也可以在节点中使用。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

#20


25  

That's how I do it:

我就是这么做的:

curl yourUri | json_pp

It shortens the code and gets the job done.

它缩短了代码并完成了任务。

#21


19  

Pygmentize

I combine Python's json.tool with pygmentize:

我把Python的json。与pygmentize工具:

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

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

在我的这个答案中,有一些关于pygze的替代方法。

Here is a live demo:

这里有一个现场演示:

如何在一个(Unix) shell脚本中打印JSON ?

#22


17  

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中包含的json_xs命令行实用程序::XS perl模块。XS是一个Perl模块,用于序列化/反序列化JSON,在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

#23


15  

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,如果您安装了JSON::来自CPAN的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


14  

  1. brew install jq
  2. 酿造安装金桥
  3. command + | jq
  4. 命令+ |金桥
  5. (example: curl localhost:5000/blocks | jq)
  6. (示例:curl localhost:5000/block | jq)
  7. Enjoy!
  8. 享受吧!

如何在一个(Unix) shell脚本中打印JSON ?

#25


11  

Install yajl-tools with the command below:

使用以下命令安装yajl工具:

sudo apt-get install yajl-tools

sudo apt-get安装yajl-tools

then,

然后,

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

echo ' {“foo”:“lorem”,“酒吧”:“添加”}”| json_reformat

#26


8  

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命令在vim中使用下面的行来在vim中打印.json文件。

autocmd FileType json setlocal equalprg=json_reformat

#27


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
 }

#28


8  

Vanilla Bash

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

一个简单的Bash脚本(grep/awk),用于漂亮的JSON打印,无需第三方安装:

json_pretty.sh

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

#29


7  

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


7  

I know this question has been replied ad nauseam, but I wanted to document a Ruby solution that is better than Json's prettify command, the gem colorful_json is fairly good.

我知道这个问题已经令人厌恶了,但是我想要记录一个比Json更好的Ruby解决方案,gem colorful_json是相当不错的。

gem install colorful_json
echo '{"foo": "lorem", "bar": "ipsum"}' | cjson
{
  "foo": "lorem",
  "bar": "ipsum"
}