Formatting JSON

In the above example, you must have seen that when you convert the Python object to JSON it does not get formatted and output comes in a straight line. We can format the JSON by passing the indent parameter to the dumps() method.

Example: Formatting JSON

Python3




# Import required libraries
import json
 
# Initialize JSON data
json_data = '[ {"studentid": 1, "name": "Nikhil", "subjects": ["Python", "Data Structures"]},\
{"studentid": 2, "name": "Nisha", "subjects": ["Java", "C++", "R Lang"]} ]'
 
# Create Python object from JSON string
# data
data = json.loads(json_data)
 
# Pretty Print JSON
json_formatted_str = json.dumps(data, indent=4)
print(json_formatted_str)


Output

[
    {
        "studentid": 1,
        "name": "Nikhil",
        "subjects": [
            "Python",
            "Data Structures"
        ]
    },
    {
        "studentid": 2,
        "name": "Nisha",
        "subjects": [
            "Java",
            "C++",
            "R Lang"
        ]
    }
]

Note: For more information, refer to Pretty Print JSON in Python

JSON with Python

JSON  (JavaScript Object Notation) is a file that is mainly used to store and transfer data mostly between a server and a web application. It is popularly used for representing structured data. In this article, we will discuss how to handle JSON data using Python. Python provides a module called json which comes with Python’s standard built-in utility.

Note: In Python, JSON data is usually represented as a string.

Similar Reads

Importing Module

To use any module in Python it is always needed to import that module. We can import json module by using the import statement....

Parsing JSON – Converting from JSON to Python

...

Convert from Python to JSON

The load() and loads() functions of the json module makes it easier to parse JSON object....

Formatting JSON

...

Sorting JSON

...

Contact Us