Pretty printing JSON String in Python

To pretty print a JSON string in Python, you can use the json.dumps(indent) method of the built-in package named json. First, you need to use the json.loads() method to convert the JSON string into a Python object. Then you need to use json.dumps() to convert the Python object back to JSON. The json.dumps() method takes a number of parameters, including the "indent" level for the JSON arrays, which will be used to pretty-print the JSON string. If the json.dumps() indentation parameter is negative 0, or an empty string, then there is no indentation, and only newlines are inserted. By default, the data is printed as a single-line JSON string without indentation. In this Python Pretty Print JSON example, we load a minified JSON string and pretty print it using json.dumps() method. Click Execute to run the Python Pretty Print JSON example online and see result.
Pretty printing JSON String in Python Execute
import json

ugly_json = '[ {"Customer": 1, "name": "Alice", "country": ["Spain", "Madrid"]}, \
                {"Customer": 2, "name": "Jack", "country": ["UK", "London"]} ]'
  
parsed_json = json.loads(ugly_json)
pretty_json = json.dumps(parsed_json, indent=2)

print(pretty_json)
Updated: Viewed: 12492 times

What is JSON?

JavaScript Object Notation (JSON) is a language-independent text format for storing and exchanging data. Developers use JSON to exchange data between a web browser and a server and exchange data between servers via REST API. Many programming languages have built-in or external libraries for creating and manipulating JSON data strings, including JavaScript, Java, C++, C#, Go, PHP, and Python. JSON file names use the .json extension.

JSON Example
{
  "Id": 78912,
  "Customer": "Jason Sweet",
  "Quantity": 1,
  "Price": 18.00
}

Pretty Print JSON in Python

To properly print a JSON string, first, use the json.loads() method to convert the JSON string into a Python object. The result object can then be converted to a pretty JSON string using the json.dumps() method. Below is an example of generating a pretty JSON string in Python.

Python Pretty Print JSON Example
import json

ugly_json = '{"Customer":"Jason Sweet","Orders":[{"Id":78912},{"Id": 88953}]}'

parsed_json = json.loads(ugly_json)

pretty_json = json.dumps(parsed_json, indent=4)

print(pretty_json)

# [
#     {
#         "Customer": 1,
#         "name": "Jack",
#         "city": [
#             "Madrid"
#         ]
#     },
#     {
#         "Customer": 2,
#         "name": "Alice",
#         "city": [
#             "London"
#         ]
#     }
# ]

See also