Pretty print json.dumps in Python
Introduction
If you need to print a dictionary or json to the console, you can do it with json.dumps
json.dumps specification
If you want to inspect the resulting json right away, you can use the dumps() method
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) Serialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump(). Note Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.
JSON
If you need to print JSON
import json
print(json.dumps(response.json(), indent=4))
Dictionary
If you need to print not JSON but a dictionary, json.dumps should be used like this:
import json
print(json.dumps(resp.dict, indent=4))
# If you need to sort the dictionary
print(json.dumps(resp.dict, indent=4, sort_keys=True))
json.dumps + json.loads
You often have to use the json.dumps + json.loads pair
import json
response_json = json.loads(response.text)
print(json.dumps(response_json, indent=4))
Access a nested object
Suppose the following comes in json
{ "address": { "version": 1, "date": "2021-Aug-11", "cities": [ { "id": "0", "name": "malaga", "place": { "id": "100", "name": "Fort", "status": "VISITED" } }, { "id": "1", "name": "benalmadena", "place": { "id": "150", "name": "Paloma Park", "status": "VISITED" } } ] } }
From it we are only interested in the status of the cities: visited or not visited.
You need to access the objects nested in the json
import json
data_set = {
"address": {
"version": 1,
"date": "2026-Nov-14",
"cities": [
{
"id": "0",
"name": "malaga",
"place": {
"id": "100",
"name": "Fort",
"status": "VISITED"
}
},
{
"id": "1",
"name": "benalmadena",
"place": {
"id": "150",
"name": "Paloma Park",
"status": "VISITED"
}
}
]
}
}
json_dump = json.dumps(data_set)
response_json = json.loads(json_dump)
cities = response_json["address"]["cities"]
for city in cities:
print(city["place"]["status"])
VISITED
VISITED
Article author: Andrei Olegovich