是否有(Unix)shell脚本将JSON格式化为可读格式?

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

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

…变成这样:

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

当前回答

我的JSON文件没有被这些方法解析。

我的问题类似于帖子“Google数据源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/.我认为这一个解析器比其他许多解析器更能容错。

其他回答

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

可读性很好的单词将被编码

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

我的JSON文件没有被这些方法解析。

我的问题类似于帖子“Google数据源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/.我认为这一个解析器比其他许多解析器更能容错。

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

使用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”}‘一样调用它。

请注意,正如@pnd在下面的注释中指出的,在Python 3.5+中,JSON对象在默认情况下不再排序。要排序,请在末尾添加--sort-keys标志。即…|python-mjson.tool——排序键。

当您的系统上安装了节点时,以下工作正常。

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

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