How to filter JSON data in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To filter JSON data in Python, you can use the built-in json module to read in the JSON data, parse it into a Python object, and then filter it using various methods. Here’s an example of how to filter a JSON array in Python:

import json

# Load the JSON data into a Python object
json_data = '[{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}, {"name": "Charlie", "age": 35}]'
data = json.loads(json_data)

# Filter the data using a list comprehension
filtered_data = [person for person in data if person['age'] > 28]

# Convert the filtered data back to JSON format and print it out
json_filtered_data = json.dumps(filtered_data)
print(json_filtered_data)

In this example, we use the json.loads() method to parse the JSON data into a Python list of dictionaries. We then use a list comprehension to filter the list based on a condition (in this case, only keeping the people older than 28 years), and store the filtered list in a variable named filtered_data. Finally, we use the json.dumps() method to convert the filtered list back into JSON format, which we print to the console. The output of this code would be:

[{"name": "Bob", "age": 30}, {"name": "Charlie", "age": 35}]

This is just one example of how to filter JSON data in Python. The approach you take will depend on the specific structure of your JSON data and the criteria you want to filter it by.

Tags: