用python (python)漂亮地打印json

时间:2021-07-21 21:44:48

I know that the pprint python standard library is for pretty-printing python data types. However, I'm always retrieving json data, and I'm wondering if there is any easy and fast way to pretty-print json data?

我知道pprint python标准库用于漂亮打印python数据类型。但是,我总是在检索json数据,我想知道是否有任何简单、快速的方法来打印json数据?

No pretty-printing:

没有精细打印:

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

With pretty-printing:

精细打印:

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

1 个解决方案

#1


60  

Python's builtin JSON module can handle that for you:

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"
}

#1


60  

Python's builtin JSON module can handle that for you:

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"
}