How to filter a JSON array in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
5 min

banner

# Table of Contents

  1. How to filter a JSON array in Python
  2. How to filter a JSON array using a for loop
  3. Filter a JSON array that is stored in a file in Python
  4. Filter a JSON array using the filter() function

# 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.
main.py
import json json_array = json.dumps( [ {'name': 'Alice', 'salary': 100}, {'name': 'Bobby', 'salary': 50}, {'name': 'Carl', 'salary': 75} ] ) a_list = json.loads(json_array) filtered_list = [ dictionary for dictionary in a_list if dictionary['salary'] > 50 ] # ๐Ÿ‘‡๏ธ [{'name': 'Alice', 'salary': 100}, {'name': 'Carl', 'salary': 75}] print(filtered_list)

filter json array

The code for this article is available on GitHub

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 50.

main.py
import json json_array = json.dumps( [ {'name': 'Alice', 'salary': 100}, {'name': 'Bobby', 'salary': 50}, {'name': 'Carl', 'salary': 75} ] ) a_list = json.loads(json_array) filtered_list = [ dictionary for dictionary in a_list if dictionary['salary'] > 50 ] # ๐Ÿ‘‡๏ธ [{'name': 'Alice', 'salary': 100}, {'name': 'Carl', 'salary': 75}] print(filtered_list)

The new list only contains the dictionaries that meet the condition.

You can use this approach to check for any condition.

Alternatively, you can use a for loop.

# How to filter a JSON array using a for loop

This is a four-step process:

  1. Use the json.loads() method to convert the JSON array to a Python list.
  2. Use a for loop to iterate over the list.
  3. Check if each list item meets a certain condition.
  4. Append the matching items to a new list.
main.py
import json json_array = json.dumps( [ {'name': 'Alice', 'salary': 100}, {'name': 'Bobby', 'salary': 50}, {'name': 'Carl', 'salary': 75} ] ) a_list = json.loads(json_array) filtered_list = [] for dictionary in a_list: if dictionary['salary'] > 50: filtered_list.append(dictionary) # ๐Ÿ‘‡๏ธ [{'name': 'Alice', 'salary': 100}, {'name': 'Carl', 'salary': 75}] print(filtered_list)

filter json array using for loop

The code for this article is available on GitHub

We used a for loop to iterate over the list.

On each iteration, we check if the current dictionary has a salary key with a value greater than 50.

If the condition is met, we use the list.append() method to append the dictionary to a new list.

The list.append() method adds an item to the end of the list.

The new list only contains the items of the original list that meet the condition.

You can use the same approach to filter a JSON array stored in a file.

# Filter a JSON array that is stored in a file in Python

To filter a JSON array that is stored in a file:

  1. Open the JSON file in reading mode.
  2. Use the JSON.load() method to deserialize the file to a Python list.
  3. Use a list comprehension to filter the list.
main.py
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: a_list = json.load(f) # ๐Ÿ‘‡๏ธ [{'name': 'Alice', 'salary': 100}, {'name': 'Bobby', 'salary': 50}, {'name': 'Carl', 'salary': 75}] print(a_list) filtered_list = [ dictionary for dictionary in a_list if dictionary['salary'] > 50 ] # ๐Ÿ‘‡๏ธ [{'name': 'Alice', 'salary': 100}, {'name': 'Carl', 'salary': 75}] print(filtered_list)

The code sample assumes that you have an example.json file stored in the same directory as your main.py script.

example.json
[ {"name": "Alice", "salary": 100}, {"name": "Bobby", "salary": 50}, {"name": "Carl", "salary": 75} ]

filter json array that is stored in file

The code for this article is available on GitHub

The json.load() method is used to deserialize a file to a Python object.

On the other hand, the json.loads() method is used to deserialize a JSON string to a Python object.

The json.load() method expects a text file or a binary file containing a JSON document that implements a .read() method.

Once we have the data from the JSON file parsed to a native Python list, we can use a list comprehension or a for loop to filter the list.

You can also use the filter() function to filter a JSON array.

# Filter a JSON array using the filter() function

This is a three-step process:

  1. Use the json.loads() function to parse the JSON array into a Python list.
  2. Pass a lambda function and the list to the filter() function.
  3. The lambda function should check if each list item meets a condition.
main.py
import json json_array = json.dumps( [ {'name': 'Alice', 'salary': 100}, {'name': 'Bobby', 'salary': 50}, {'name': 'Carl', 'salary': 75} ] ) a_list = json.loads(json_array) filtered_list = list( filter( lambda dictionary: dictionary['salary'] > 50, a_list ) ) # ๐Ÿ‘‡๏ธ [{'name': 'Alice', 'salary': 100}, {'name': 'Carl', 'salary': 75}] print(filtered_list)

filter json array using filter function

The code for this article is available on GitHub

The filter() function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

The lambda function we passed to filter() gets called with each dictionary from the list.

The function checks if the dictionary meets a certain condition and returns the result.

The last step is to use the list() class to convert the filter object to a list.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev