116

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())
3
  • Why don't you use pprint? Commented May 18, 2014 at 5:37
  • In your example you're not printing JSON anywhere. You decode it (by doing r.json()), so it's just a Python data structure after that. So what exactly do you want to pretty print? Python data structures or JSON? Commented May 18, 2014 at 8:21
  • mmm you're right. Both cases. Commented May 19, 2014 at 7:06

7 Answers 7

155

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"
}
Sign up to request clarification or add additional context in comments.

2 Comments

weird, getting / separated string in notebook output
The indent=2 is what brought the magic to me. Tried without it first and got nothing but a wall of entries.
29
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))

1 Comment

The variable name pretty_json is misleading. The JSON isn't "pretty" until it's run through json.dumps().
25

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

2 Comments

Please put your answer always in context instead of just pasting code. See here for more details.
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
6

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

Comments

2

Use for show unicode values and key.

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

Comments

1

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

2 Comments

Please, add some explanation to your code.
There is a typo in your imports, always be sure to test your code before posting it as an answer
0

These answers are good if you want to print the entire json/dict. However, there are times when you only want the "outline", since the values are too long. In this case you can use this:

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)

The output is:

a
  b
    dict_list
      c
      d
  e
    f
g

In this implementation, if the value of a dictionary key is a list of dictionaries, we first check if the list has any elements. If it does, we define the keys of the first dictionary in the list, and print them as subheadings of 'dict_list'. We do not print the values for each dictionary in the list, only the keys. This allows us to print an outline of the nested dictionary that includes subheadings for each list of dictionaries, without printing the individual values of each dictionary.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.