如何用Python打印JSON文件?


当前回答

这里有一个简单的例子,可以用Python将JSON以一种很好的方式打印到控制台,而不需要将JSON作为本地文件存储在计算机上:

import pprint
import json 
from urllib.request import urlopen # (Only used to get this example)

# Getting a JSON example for this example 
r = urlopen("https://mdn.github.io/fetch-examples/fetch-json/products.json")
text = r.read() 

# To print it
pprint.pprint(json.loads(text))

其他回答

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

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

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

结果如下:

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

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

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

from rich import print_json

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

使用pprint:https://docs.python.org/3.6/library/pprint.html

import pprint
pprint.pprint(json)

print()与pprint.pprint()比较

print(json)
{'feed': {'title': 'W3Schools Home Page', 'title_detail': {'type': 'text/plain', 'language': None, 'base': '', 'value': 'W3Schools Home Page'}, 'links': [{'rel': 'alternate', 'type': 'text/html', 'href': 'https://www.w3schools.com'}], 'link': 'https://www.w3schools.com', 'subtitle': 'Free web building tutorials', 'subtitle_detail': {'type': 'text/html', 'language': None, 'base': '', 'value': 'Free web building tutorials'}}, 'entries': [], 'bozo': 0, 'encoding': 'utf-8', 'version': 'rss20', 'namespaces': {}}

pprint.pprint(json)
{'bozo': 0,
 'encoding': 'utf-8',
 'entries': [],
 'feed': {'link': 'https://www.w3schools.com',
          'links': [{'href': 'https://www.w3schools.com',
                     'rel': 'alternate',
                     'type': 'text/html'}],
          'subtitle': 'Free web building tutorials',
          'subtitle_detail': {'base': '',
                              'language': None,
                              'type': 'text/html',
                              'value': 'Free web building tutorials'},
          'title': 'W3Schools Home Page',
          'title_detail': {'base': '',
                           'language': None,
                           'type': 'text/plain',
                           'value': 'W3Schools Home Page'}},
 'namespaces': {},
 'version': 'rss20'}

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

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

你可以改进它,添加缩进等等,但是如果你只是想读一个更干净的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)