如何用Python打印JSON文件?


当前回答

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

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

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

其他回答

我有一个类似的要求来转储json文件的内容以进行日志记录,这是一种快速而简单的方法:

print(json.dumps(json.load(open(os.path.join('<myPath>', '<myjson>'), "r")), indent = 4 ))

如果您经常使用它,请将其放在函数中:

def pp_json_file(path, file):
    print(json.dumps(json.load(open(os.path.join(path, file), "r")), indent = 4))

使用这个函数,不用担心,你必须再次记住你的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)

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

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

输出

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

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

from rich import print_json

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