pretty-print json in python (pythonic way)

PythonJson

Python Problem Overview


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?

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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

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

Solution 5 - Python

Use for show unicode values and key.

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

Solution 6 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionautorunView Question on Stackoverflow
Solution 1 - PythonsvvacView Answer on Stackoverflow
Solution 2 - PythonHolmesView Answer on Stackoverflow
Solution 3 - PythonAnbratenView Answer on Stackoverflow
Solution 4 - PythonEugene Gr. PhilippovView Answer on Stackoverflow
Solution 5 - PythonquickesView Answer on Stackoverflow
Solution 6 - PythonNirakar NepalView Answer on Stackoverflow