Skip to content

Python JSON dumps indent | Example

  • by

Python JSON method used indent parameters to specify the spaces that are used at the beginning of a line. If the indent parameter is not used By default it doesn’t use indentations and writes all data on a single line, which is not readable.

Example use JSON dumps indent in Python

A simple example code uses the indent parameter of json. dump() to specify the indentation value.

Pretty-Printed JSON data into a file with indent=4

import json

data = '[{"ID":101,"Name":"John","Class":"First"},' \
       '{"ID":102,"Name":"Tim","Class":"Second"}]'

res = json.loads(data)

# Indent = 3
print(json.dumps(res, indent=4))

Output:

Python JSON dumps indent

How to prettyprint a JSON file?

Answer: The json module already implements some basic pretty printing with the indent parameter that specifies how many spaces to indent by:

import json

data = '["foo", {"bar":["baz", null, 1.0, 2]}]'
res = json.loads(data)

print(json.dumps(res, indent=4, sort_keys=True))

Output:

prettyprint a JSON file indent

Source: stackoverflow.com/

Do comment if you have any doubts or suggestions on this Python JSON topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading