如何在shell脚本中打印JSON?

时间:2008-12-09 08:20:45

标签: json unix command-line format pretty-print

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

基本上,我希望它能改变以下内容:

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

...变成这样的东西:

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

58 个答案:

答案 0 :(得分:4071)

使用Python 2.6+,您可以这样做:

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

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

python -m json.tool my_json.json

如果JSON来自互联网源,例如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"}'一样调用它。

答案 1 :(得分:814)

您可以使用:jq

使用非常简单,效果很好!它可以处理非常大的JSON结构,包括流。你可以找到 他们的教程here

以下是一个例子:

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

或换句话说:

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

答案 2 :(得分:366)

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

答案 3 :(得分:328)

我写了一个工具,它有一个最好的“智能空白”格式化器。它比这里的大多数其他选项产生更可读,更简洁的输出。

underscore-cli

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

我可能有点偏颇,但它是从命令行打印和操作JSON数据的一个很棒的工具。它使用起来非常友好,并提供广泛的命令行帮助/文档。这是一把瑞士军刀,我用它来完成1001个不同的小任务,以任何其他方式令人惊讶地烦恼。

最新用例:Chrome,开发控制台,网络标签,全部导出为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

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

答案 4 :(得分:171)

我通常只是这样做:

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

答案 5 :(得分:85)

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

答案 6 :(得分:72)

如果使用npm和Node.js,则可以执行npm install -g json,然后通过json传递命令。 json -h可以获得所有选项。它还可以提取特定字段并使用-i将输出着色。

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

答案 7 :(得分:71)

使用the jq tools的原生方式并不太简单。

例如:

cat xxx | jq .

答案 8 :(得分:68)

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

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

答案 9 :(得分:68)

使用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的“扩展系统”)。

答案 10 :(得分:64)

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

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

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

答案 11 :(得分:55)

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

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

来自自述文件:

  

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

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

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

jsonpp data/long_malformed.json

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

中的某个位置即可

答案 12 :(得分:51)

试试pjson。它有颜色!

echo '{"json":"obj"} | pjson

使用pip

进行安装

⚡ pip install pjson

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

答案 13 :(得分:48)

我就是这样做的:

curl yourUri | json_pp

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

答案 14 :(得分:42)

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

可读性很好的单词变为\ uc编码

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

如果您的管道的其余部分将优雅地处理unicode,并且您希望您的JSON也是人性化的,那么只需use 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"
}

答案 15 :(得分:39)

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

echo $COMPACTED_JSON_TEXT | jshon

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

答案 16 :(得分:37)

或者,使用Ruby:

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

答案 17 :(得分:36)

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

gem install jazor
jazor --help

答案 18 :(得分:29)

一个简单的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

答案 19 :(得分:29)

只需将输出传送到jq .

示例:

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

答案 20 :(得分:29)

JSONLint有一个open-source implementation on GitHub,可以在命令行中使用或包含在Node.js项目中。

npm install jsonlint -g

然后

jsonlint -p myfile.json

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

答案 21 :(得分:23)

Pygmentize

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

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

my this answer中列出了pygmentize的一些替代方法。

这是一个现场演示:

Demo

答案 22 :(得分:19)

使用Perl,如果从CPAN安装JSON::PP,您将获得json_pp命令。从example偷取B Bycroft你得到:

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

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

答案 23 :(得分:19)

我建议使用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

答案 24 :(得分:17)

您可以使用以下简单命令来获得结果:

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

答案 25 :(得分:16)

  1. brew install jq
  2. command + | jq
  3. (例如:curl localhost:5000/blocks | jq
  4. 享受!
  5. enter image description here

答案 26 :(得分:15)

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

jj -p # for reading from STDIN

jj -p -i input.json

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

答案 27 :(得分:14)

您可以简单地使用jq或json_pp之类的标准工具。

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

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

都会像下面这样美化输出(jq更加丰富多彩):

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

jq的巨大优势在于,如果您想解析和处理json,它可以做更多的事情。

答案 28 :(得分:12)

batcat的克隆,其语法突出显示:

示例:

echo '{"bignum":1e1000}' | bat -p -l json

-p将不带标题输出,而-l将显式指定语言。

它具有JSON的颜色和格式,并且没有此注释中指出的问题: How can I pretty-print JSON in a shell script?

答案 29 :(得分:11)

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

sudo apt-get install yajl-tools

然后,

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

答案 30 :(得分:10)

在一行中使用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

Enter image description here

答案 31 :(得分:10)

根据我的经验,

yajl非常好。我使用json_reformat命令在.json中通过将以下行添加到vim中来精确打印.vimrc个文件:

autocmd FileType json setlocal equalprg=json_reformat

答案 32 :(得分:9)

PHP版本,如果你有PHP&gt; = 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

答案 33 :(得分:8)

当您的系统上安装了节点后,以下工作将起作用。

echo '{"test":1,"test2":2}' | npx json

{
  "test": 1,
  "test2": 2
}

答案 34 :(得分:8)

我正在使用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
 }

答案 35 :(得分:7)

这是一个比Json的美化命令更好的Ruby解决方案。宝石colorful_json相当不错。

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

答案 36 :(得分:7)

J.F。 Sebastian的解决方案在Ubuntu 8.04中对我不起作用 这是一个修改过的Perl版本,适用于旧的1.X JSON库:

perl -0007 -MJSON -ne 'print objToJson(jsonToObj($_, {allow_nonref=>1}), {pretty=>1}), "\n";'

答案 37 :(得分:6)

$ sudo apt-get install edit-json
$ prettify_json myfile.json

答案 38 :(得分:5)

工具ydump是一台JSON漂亮的打印机:

$ ydump my_data.json
{
  "foo": "lorem",
  "bar": "ipsum"
}

或者你可以输入JSON:

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

除了使用jq工具之外,这可能是最短的解决方案。

此工具是OCamlyojson库的一部分,并记录在案here

在Debian和衍生产品上,包libyojson-ocaml-dev包含此工具。或者,可以通过OPAM安装yojson

答案 39 :(得分:4)

以下是使用Groovy脚本执行此操作的方法。

创建一个Groovy脚本,让我们说“漂亮的打印”

#!/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

答案 40 :(得分:4)

使用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 ))"

答案 41 :(得分:4)

TidyJSON

这是C#,所以也许你可以使用Mono进行编译,然后使用* nix。不过没有保证,抱歉。

答案 42 :(得分:4)

对于Node.js,你也可以使用&#34; util&#34;模块。它使用语法高亮,智能缩进,从键中删除引号,并使输出尽可能美观。

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

答案 43 :(得分:3)

如果安装了Node.js,您可以使用一行代码自行创建一个。创建一个漂亮的文件:

  

&GT; vim pretty

respond_to

添加执行权限:

  

&GT; chmod + x pretty

     

&GT; ./pretty&#39; {&#34; foo&#34;:&#34; lorem&#34;,&#34; bar&#34;:&#34; ipsum&#34;}&#39;

或者,如果您的JSON在文件中:

respond_to do |format|
   format.html  { render :new } 
   format.json  { render json: { ... } }
end
  

&GT; ./pretty file.json

答案 44 :(得分:3)

使用JavaScript / Node.js:看看vkBeautify.js plugin,它为JSON和XML文本提供了漂亮的打印。

它是用纯JavaScript编写的,小于1.5 KB(缩小)并且非常快。

答案 45 :(得分:3)

我是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

答案 46 :(得分:3)

TL; DR :要进行表演,请使用jj -p < my.json

基准

我在这里采用了一些解决方案,并用下一个虚拟脚本对它们进行了基准测试:

function bench {
    time (
      for i in {1..100}; do
        echo '{ "foo": "lorem", "bar": "ipsum" }'  | $@ > /dev/null
      done
    )
}

这是我的Mac(8 GB 2133 MHz LPDDR3、2.3 GHz Intel Core i5)上的结果:

bench python -m json.tool
# 3.60s user 1.24s system 88% cpu 5.448 total
bench jq
# 2.79s user 0.29s system 89% cpu 3.453 total
bench bat -p -l json
# 5.77s user 0.99s system 95% cpu 7.080 total
bench jj -p
# 0.19s user 0.26s system 85% cpu 0.529 total

感谢@peak和您的answer对jj的发现!

答案 47 :(得分:3)

我想出了这个解决方案: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,你就可以使用这个功能。

您是否在另一台无法安装任何东西的主机上,这将是该问题的完美解决方案。

答案 48 :(得分:2)

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

答案 49 :(得分:2)

这是一个Groovy单行:

echo '{"foo": "lorem", "bar": "ipsum"}' | groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'

答案 50 :(得分:2)

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

此方法也"Detects HTTP response/headers, prints them untouched, and skips to the body (for use with `curl -i')"

答案 51 :(得分:1)

我的JSON文件未被任何这些方法解析。

我的问题类似于帖子 Is Google data source JSON not valid?

The answer to that post帮助我找到了解决方案。

没有字符串键,它被认为是无效的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/。我认为这个解析器比其他解析器更容错。

答案 52 :(得分:1)

您可以使用smk

from pyglet.gl import *

class Triangle:
    def __init__(self):
        self.vertices = pyglet.graphics.vertex_list(3, ('v3f', [0,0,0, 300,0,0, 150,300,0]),
                                                       ('c3B', [255,0,0, 0,255,0, 0,0,255]))

    def draw(self):
        self.vertices.draw(GL_TRIANGLES)


class MyWindow(pyglet.window.Window):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.set_minimum_size(400, 300)
        glClearColor(0.2, 0.25, 0.2, 1.0)

        glOrtho(0, 1280, 0, 720, -10, 10) # setup orthogonal projection

        self.triangle = Triangle()

    def on_draw(self):
        self.clear()
        glPushMatrix()
        glTranslatef(640-150 ,360-150, 0) # translate the Triangle to the center
        self.triangle.draw()
        glPopMatrix()

    def on_resize(self, width, height):
        glViewport(0, 0, width, height) # resize the viewport


if __name__ == "__main__":
    MyWindow(1280, 720, 'My window', resizable=True)
    pyglet.app.run()

一行

echo '{"foo": "lorem", "bar": "ipsum"}' | smk -e"JSON.stringify(JSON.parse(data), null, 4)"

答案 53 :(得分:0)

答案 54 :(得分:0)

如果您不介意使用第三方工具,则可以卷曲jsonprettyprint.org。这适用于无法在计算机上安装软件包的情况。

curl -XPOST https://jsonprettyprint.org/api -d '{"user" : 1}'

答案 55 :(得分:0)

您可以使用Xidel

  

Xidel是一个命令行工具,可以使用CSS,XPath 3.0,XQuery 3.0,JSONiq或模式模板从HTML / XML页面或JSON-API下载和提取数据。它还可以创建新的或转换后的XML / HTML / JSON文档。

默认情况下,Xidel漂亮打印:

.free-tote-second-div {
      position: fixed;
      bottom: 0px;
}

或:

$ xidel -s - -e '$json' <<< '{"foo":"lorem","bar":"ipsum"}'
{
  "foo": "lorem",
  "bar": "ipsum"
}

答案 56 :(得分:-3)

我知道原帖要求提供shell脚本,但是有很多有用且无关的答案可能对原作者没有帮助。 加上无关紧要:)

BTW我无法使用任何命令行工具。

如果有人想要简单的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
     }
}

OR(只是按键排序):

{
 "a": {
      "a1": 1,
      "b1": 2
 },
 "b": 1,
 "c": 1
}

答案 57 :(得分:-3)

如果您可以选择使用在线工具,也可以使用在线工具。

我发现http://jsonprettyprint.net是最简单最容易的。