Sorting JSON

We can sort the JSON data with the help of the sort_keys parameter of the dumps() method. This parameter takes a boolean value and returns the sorted JSON if the value passed is True. By default, the value passed is False.

Example: Sorting JSON

Python3




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


Output

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


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