Home » How to filter a JSON array in Python
How to learn python

How to filter a JSON array in Python

How to filter a JSON array in Python

To filter a JSON array in Python:

  1. Use the json.loads() method to convert the JSON array to a Python list.
  2. Use a list comprehension to iterate over the list.
  3. 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.

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Chat Icon