Python sort json by specific key

Sorting JSON by specific key in Python

To sort a JSON object by a specific key in Python, you can make use of the sorted() function along with a lambda function to specify the key for sorting.

Here’s an example:

import json

# Sample JSON data
json_data = '''
{
    "employees": [
        {
            "name": "John",
            "age": 30,
            "position": "Manager"
        },
        {
            "name": "Alice",
            "age": 25,
            "position": "Developer"
        },
        {
            "name": "Bob",
            "age": 35,
            "position": "Designer"
        }
    ]
}
'''

# Load JSON data into a Python object
data = json.loads(json_data)

# Sort the "employees" array based on the "age" key
sorted_data = sorted(data['employees'], key=lambda x: x['age'])

# Convert the sorted object back to JSON
sorted_json = json.dumps(sorted_data)

print(sorted_json)
    

In the above example, we have a JSON object representing employee data. We want to sort the list of employees based on their age.

We first load the JSON data using the json.loads() function to convert it into a Python object. Then, we use the sorted() function to sort the “employees” array based on the “age” key. Here, the lambda function lambda x: x['age'] specifies that we want to sort based on the “age” key. Finally, we use the json.dumps() function to convert the sorted object back to JSON.

The output of the above code will be:

[
    {
        "name": "Alice",
        "age": 25,
        "position": "Developer"
    },
    {
        "name": "John",
        "age": 30,
        "position": "Manager"
    },
    {
        "name": "Bob",
        "age": 35,
        "position": "Designer"
    }
]
    

As you can see, the “employees” array is now sorted based on the “age” key in ascending order.

Leave a comment