Working with JSON data is a common operation when dealing with APIs, databases, or other data sources in Python. Sometimes, you might find yourself needing to sort a JSON array based on a specific key.
In such a scenario, Python comes with inbuilt functionality that allows you to effectively sort a JSON array based on a Key. This tutorial will guide you step-by-step on how to achieve that.
Step 1: Importing the Necessary Module
In order to work with JSON data in Python, we need to import the json module which is a part of the standard library, so no additional installation is needed. Here is how you do it:
1 |
import json |
Step 2: Defining Your JSON Array
Next, let’s define a JSON array we will work with. For this tutorial, we will use the following array of JSON objects:
1 2 3 4 5 6 7 |
json_array = ''' [ {"name": "John", "age": 30, "city": "New York"}, {"name": "Jane", "age": 25, "city": "Chicago"}, {"name": "Dave", "age": 50, "city": "San Francisco"} ] ''' |
Step 3: Loading Your JSON Array into Python
In order for Python to manipulate our JSON array, we must load it into a Python data structure using json.loads method:
1 |
data_python = json.loads(json_array) |
Step 4: Sorting the JSON Array
To sort the JSON array based on a key, we will use the sorted() function in Python:
1 |
sorted_python = sorted(data_python, key=lambda x: x['age']) |
This will sort our JSON array in ascending order based on the ‘age’ key. If you wish to sort in descending order, you can add the reverse=True parameter. replace the code ‘x[‘age’]’ with the key on which you wish to sort the JSON array.
Full Python Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import json json_array = ''' [ {"name": "John", "age": 30, "city": "New York"}, {"name": "Jane", "age": 25, "city": "Chicago"}, {"name": "Dave", "age": 50, "city": "San Francisco"} ] ''' data_python = json.loads(json_array) sorted_python = sorted(data_python, key=lambda x: x['age']) print(sorted_python) |
Output
1 2 3 |
[{'name': 'Jane', 'age': 25, 'city': 'Chicago'}, {'name': 'John', 'age': 30, 'city': 'New York'}, {'name': 'Dave', 'age': 50, 'city': 'San Francisco'}] |
Conclusion
You have now learned how to sort a JSON array based on a key in Python. You can now incorporate this functionality into your API managing or database organizing projects.
Remember, the key to mastery is consistent practice so keep working on projects where you can apply this knowledge. Happy coding!