在 python 中漂亮打印 json (pythonic way)

我知道 pprint python 标准库是用于漂亮打印 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())
117706 次浏览

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

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

I used following code to directly get a json output from my requests-get result and pretty printed this json object with help of pythons json libary function .dumps() by using indent and sorting the object keys:

import requests
import json


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

Use for show unicode values and key.

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

Here's a blend of all answers and an utility function to not repeat yourself:

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

#This Should work

import requests
import json


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