如何用Python打印JSON文件?


当前回答

为了能够从命令行进行漂亮的打印并能够控制缩进等,您可以设置类似于以下内容的别名:

alias jsonpp="python -c 'import sys, json; print json.dumps(json.load(sys.stdin), sort_keys=True, indent=2)'"

然后以以下方式之一使用别名:

cat myfile.json | jsonpp
jsonpp < myfile.json

其他回答

一个非常简单的方法是使用rich。使用此方法,您还可以突出显示json

此方法从名为config.json的json文件中读取数据

from rich import print_json

setup_type = open('config.json')
data = json.load(setup_type)
print_json(data=data)

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

您可以尝试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

输出

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

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

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

我认为最好先解析json,以避免错误:

def format_response(response):
    try:
        parsed = json.loads(response.text)
    except JSONDecodeError:
        return response.text
    return json.dumps(parsed, ensure_ascii=True, indent=4)