如何用Python打印JSON文件?


当前回答

使用这个函数,不用担心,你必须再次记住你的JSON是str还是dict-看看漂亮的打印:

import json

def pp_json(json_thing, sort=True, indents=4):
    if type(json_thing) is str:
        print(json.dumps(json.loads(json_thing), sort_keys=sort, indent=indents))
    else:
        print(json.dumps(json_thing, sort_keys=sort, indent=indents))
    return None

pp_json(your_json_string_or_dict)

其他回答

Pygmentize是为终端命令的输出着色的强大工具。

下面是一个使用它向json.tool输出添加语法高亮显示的示例:

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

结果如下:

在前面的堆栈溢出回答中,我详细介绍了如何安装和使用pygmentize。

这远不是完美的,但它确实起到了作用。

data = data.replace(',"',',\n"')

你可以改进它,添加缩进等等,但是如果你只是想读一个更干净的json,这就是方法。

您可以尝试pprintjson。


安装

$ pip3 install pprintjson

用法

使用pprintjson CLI从文件中精确打印JSON。

$ pprintjson "./path/to/file.json"

使用pprintjson CLI从stdin打印JSON。

$ echo '{ "a": 1, "b": "string", "c": true }' | pprintjson

使用pprintjson CLI从字符串中精确打印JSON。

$ pprintjson -c '{ "a": 1, "b": "string", "c": true }'

从缩进为1的字符串中精确打印JSON。

$ pprintjson -c '{ "a": 1, "b": "string", "c": true }' -i 1

从字符串中精确打印JSON并将输出保存到文件output.JSON。

$ pprintjson -c '{ "a": 1, "b": "string", "c": true }' -o ./output.json

输出

使用json.dump()或json.dumps()的indent关键字参数指定要使用的缩进量:

>>> import json
>>>
>>> your_json = '["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4))
[
    "foo",
    {
        "bar": [
            "baz",
            null,
            1.0,
            2
        ]
    }
]

要解析文件,请使用json.load():

with open('filename.txt', 'r') as handle:
    parsed = json.load(handle)
def saveJson(date,fileToSave):
    with open(fileToSave, 'w+') as fileToSave:
        json.dump(date, fileToSave, ensure_ascii=True, indent=4, sort_keys=True)

它可以将其显示或保存到文件中。