在Python中漂亮地打印JSON(Pythonic方式)

112
我知道Python标准库中的pprint是用于漂亮地打印Python数据类型,但我总是获取JSON数据,想知道有没有一种简单快捷的方法来漂亮地打印JSON数据?

无漂亮打印:

import requests
r = requests.get('http://server.com/api/2/....')
r.json()

使用漂亮的打印:

>>> import requests
>>> from pprint import pprint
>>> r = requests.get('http://server.com/api/2/....')
>>> pprint(r.json())

为什么不使用 pprint - thefourtheye
在你的例子中,你没有打印 JSON 任何地方。你解码它(通过 r.json()),所以在那之后它只是一个 Python 数据结构。那么你到底想要漂亮打印什么?Python 数据结构还是 JSON? - Lukas Graf
没错,你说得对。两种情况都是。 - autorun
7个回答

148

Python内置的JSON模块可以为您处理此操作:

>>> import json
>>> a = {'hello': 'world', 'a': [1, 2, 3, 4], 'foo': 'bar'}
>>> print(json.dumps(a, indent=2))
{
  "hello": "world",
  "a": [
    1,
    2,
    3,
    4
  ],
  "foo": "bar"
}

8
奇怪,在笔记本输出中获取 / 分隔字符串 - Kermit
indent=2 是让我感到神奇的地方。一开始没有使用它,只看到一堵堵的条目墙。 - undefined

27
import requests
import json
r = requests.get('http://server.com/api/2/....')
pretty_json = json.loads(r.text)
print (json.dumps(pretty_json, indent=2))

22

我使用以下代码直接从requests-get结果中获取JSON输出,并借助Python的JSON库函数.dumps()使用缩进和排序对象键来美化打印此JSON对象:

import requests
import json

response = requests.get('http://example.org')
print (json.dumps(response.json(), indent=4, sort_keys=True))

1
请始终将您的答案放在上下文中,而不仅仅是粘贴代码。有关更多详细信息,请参见此处 - gehbiszumeis
2
虽然这段代码可能回答了问题,但提供有关它如何以及/或为什么解决问题的附加上下文将改善答案的长期价值。 - Piotr Labunski

6

这里是所有答案的混合以及一个实用函数,以免重复:

import requests
import json

def get_pretty_json_string(value_dict):
    return json.dumps(value_dict, indent=4, sort_keys=True, ensure_ascii=False)

# example of the use
response = requests.get('http://example.org/').json()
print (get_pretty_json_string (response))

2

用于显示Unicode值和键。

print (json.dumps(pretty_json, indent=2, ensure_ascii=False))

0

#这应该可以工作

import requests
import json

response = requests.get('http://server.com/api/2/....')
formatted_string = json.dumps(response.json(), indent=4)
print(formatted_string)

请在您的代码中添加一些解释。 - Shunya
1
你的导入中有一个拼写错误,请在发布答案之前一定要测试你的代码。 - 0x263A

0

如果你想打印整个JSON /字典,这些答案是很好的。然而,有时候你只想要“大纲”,因为值太长了。在这种情况下,你可以使用以下代码:

def print_dict_outline(d, indent=0):
    for key, value in d.items():
        print(' ' * indent + str(key))
        if isinstance(value, dict):
            print_dict_outline(value, indent+2)
        elif isinstance(value, list) and all(isinstance(i, dict) for i in value):
            if len(value) > 0:
                keys = list(value[0].keys())
                print(' ' * (indent+2) + 'dict_list')
                for k in keys:
                    print(' ' * (indent+4) + str(k))

# Example dictionary with a list of dictionaries
my_dict = {
    'a': {
        'b': [
            {'c': 1, 'd': 2},
            {'c': 3, 'd': 4}
        ],
        'e': {
            'f': 5
        }
    },
    'g': 6
}

# Print the outline of the dictionary
print_dict_outline(my_dict)

输出结果为:

a
  b
    dict_list
      c
      d
  e
    f
g

在这个实现中,如果字典键的值是一个字典列表,我们首先检查列表是否有任何元素。如果有,我们定义列表中第一个字典的键,并将它们作为“dict_list”的子标题打印出来。我们不打印列表中每个字典的值,只打印键。这使我们能够打印嵌套字典的大纲,其中包括每个字典列表的子标题,而不打印每个字典的单个值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接