How to filter a JSON array in Python
To filter a JSON array in Python:
- Use the
json.loads()
method to convert the JSON array to a Python list. - Use a list comprehension to iterate over the list.
- Check if each item in the list meets a certain condition and return the result.
import json
json_array = json.dumps(
[
{'name': 'Daim Dev', 'salary': 1000},
{'name': 'Jimm', 'salary': 5000},
{'name': 'Carl', 'salary': 750}
]
)
a_list = json.loads(json_array)
filtered_list = [
dictionary for dictionary in a_list
if dictionary['salary'] > 2000
]
# 👇️ [{'name': 'Jimm', 'salary': 5000}, {'name': 'Carl', 'salary': 750}]
print(filtered_list)
The json.dumps()
method converts a Python object to a JSON formatted string.
Conversely, the json.loads()
method parses a JSON string into a native Python object.
We used the json.loads()
method to convert the JSON array to a native Python list.
We then used a list comprehension to iterate over the list.
On each iteration, we check if a certain condition is met and return the result.
The code sample checks if each dictionary has a salary
key with a value greater than 2000.
How to filter a JSON array in Python