The JSON file is a very popular medium to exchange data between different types of programming languages. It is a language-independent text-based file format that stores data by using an array and object. It can store numbers, strings, Boolean, and another array or object as the content. The JSON object can be sorted by using built-in python functions, modules, and user-defined functions. Different ways to sort the JSON object in Python have been explained in this tutorial.

Example-1: Sort JSON object using json.dumps()

Using json.dumps() function is one way to sort the JSON object. It is used to convert the array of JSON objects into a sorted JSON object. The value of the sort_keys argument of the dumps() function will require to set True to generate the sorted JSON objects from the array of JSON objects. Create a python file with the following script sort the JSON objects using json.dumps() function. Both the original and sorted JSON objects will be printed after executing the script.

# Import the JSON module

import json

# Array of JSON Objects


products = [{“name”: “HDD”, “brand”: “Samsung”, “price”: 100},


            {“name”: “Monitor”, “brand”: “Dell”, “price”: 120},


            {“name”: “Mouse”, “brand”: “Logitech”, “price”: 10}]

# Read and print the original data

print(“The original data:n{0}”.format(products))

# Convert into the JSON object after sorting


sorted_json_data = json.dumps(products, sort_keys=True)

# Print the sorted JSON data

print(“The sorted JSON data based on the keys:n{0}”.format(sorted_json_data))

Output:

the following output will appear after executing the script. Each JSON object contains three key-value pairs in the JSON array. The values of the objects have sorted based on the keys in the output. According to the key value, the brand key has appeared first, and the price key appeared last based on the sort.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/07/echo/1-15.png" data-lazy- height="393" src="data:image/svg xml,” width=”1030″>

Example-2: Sort JSON object using lambda

Using lambda in the sort() function is another way to sort JSON objects. Create the python file with the following script to sort JSON objects using sort() and the lambda function. The particular key or keys can be mentioned for sorting when the lambda is used for sorting. In the following script, the same array of JSON objects has used that was used in the previous example. Three keys exist in the JSON objects. These are name, brand, and price. The ‘brand’ key has mentioned in the sort() for the sorting key. So, the JSON objects will be sorted based on the values of the ‘brand’ key. Both the original values and the sorted values will be printed as output.

# Array of JSON Objects


products = [{“name”: “HDD”, “brand”: “Samsung”, “price”: “$100”},


            {“name”: “Monitor”, “brand”: “Dell”, “price”: “$120”},


            {“name”: “Mouse”, “brand”: “Logitech”, “price”: “$10”}]

# Print the original data

print(“The original JSON data:n{0}”.format(products))

# Sort the JSON data based on the value of the brand key


products.sort(key=lambda x: x[“brand”])

# Print the sorted JSON data

print(“The sorted JSON data based on the value of the brand:n{0}”.format(products))

Output:

the following output will appear after executing the script. Three brand values defined in the script are Samsung, Dell, and Logitech. After sorting, the object containing the product of the ‘Dell‘ brand has appeared first, and the object containing the ‘Samsung‘ brand has appeared last in the output.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/07/echo/2-14.png" data-lazy- height="396" src="data:image/svg xml,” width=”1024″>

Example-3: Sort JSON object using sorted function

Create a python file with the following script to sort the JSON objects by using the pprint module and the sorted() function. The pprint module is imported into the script to use the pprint() function to format the JSON output. An array of four JSON objects has been declared in the script. Each object contains three key-value pairs. The keys are name, post, and email. A user-defined function named sort_by_key() is declared to sort the JSON objects based on the value of the ‘name‘ key. This function is called in the sorted() function by using the argument named key. After executing the sorted() function, the JSON objects will be printed by sorting the objects based on the values of the name key.

# import pprint module

import pprint

# Array of JSON Objects


employee_list = [

{


    ‘name’: ‘firoz shah’,


    ‘post’: ‘HR’,


    ’email’: ‘Accountant’

},

{


    ‘name’: ‘Aiyan hasan’,


    ‘post’: ‘Sales’,


    ’email’: ‘Manager’

},

{


    ‘name’: ‘Mahmuda Feroz’,


    ‘post’: ‘Marketing’,


    ’email’: ‘CEO’

}]

# Print the original JSON list

print(“Array of JSON objects before sorting:”)

pprint.pprint(employee_list)

# Declare function to return the sorted data based on name

def sort_by_key(list):


    return list[‘name’]

# Print the sorted JSON list based on the name key

print(nArray of JSON objects after sorting:”)

pprint.pprint(sorted(employee_list, key=sort_by_key))

Output:

The following output will appear after executing the above script. Three values of the name key defined in the script are ‘firoz shah’, ‘Aiyan hasan’, and ‘Mahmuda Feroz’. After sorting, the JSON object that contains ‘Aiyan hasan’ in the name key has appeared first, and the JSON object that contains Mahmuda Feroz’ in the name key has appeared last in the output.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/07/echo/3-14.png" data-lazy- height="448" src="data:image/svg xml,” width=”1027″>

Example-4: Sort JSON objects in descending order

The JSON objects have sorted in ascending order in the previous three examples. The way to sort the JSON object in descending order based on a particular key value has shown in this example. Create a python file with the following script that will sort the JSON objects in descending order based on the value of the price key.

import pprint

# Array of JSON Objects


products = [{“name”: “HDD”, “brand”: “Samsung”, “price”: “$100”},


            {“name”: “Monitor”, “brand”: “Dell”, “price”: “$120”},


            {“name”: “Mouse”, “brand”: “Logitech”, “price”: “$10”}]

”’


Print the sorted JSON objects in descending order


based on the price key value


”’


print(nArray of JSON objects after sorting:”)


products = sorted(products, key=lambda k: k[‘price’], reverse=True)

pprint.pprint((products))

Output:

The following output will appear after executing the above script. After sorting the JSON objects, the object containing the highest price value has appeared first, and the object containing the lowest price value has appeared last in the output.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/07/echo/4-14.png" data-lazy- height="444" src="data:image/svg xml,” width=”1027″>

Conclusion:

Four different ways to sort the JSON objects have been shown in this tutorial by using various examples. The sort(), sorted(), and dumps() functions have been used here to sort the JSON object in ascending and descending order.

About the author

<img alt="" data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/07/echo/channel-logo-150×150.jpg60ef08203625d.jpg" height="112" src="data:image/svg xml,” width=”112″>

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.