How to filter nested json data in python

To filter nested JSON data in Python, you can use the filter() function along with lambda functions. The lambda function can be used to define the filtering conditions based on the required criteria.

Here is an example to illustrate the process:


import json
  
# Sample JSON data
data = {
  "employees": [
    {
      "name": "John",
      "age": 30,
      "department": "IT"
    },
    {
      "name": "Jane",
      "age": 35,
      "department": "HR"
    },
    {
      "name": "Mike",
      "age": 28,
      "department": "Finance"
    }
  ]
}

# Filter employees younger than 30
filtered_data = list(filter(lambda x: x['age'] < 30, data['employees']))

print(json.dumps(filtered_data, indent=2))
  

In this example, the JSON data consists of an "employees" list, and each element of the list represents an employee with various attributes (name, age, department). We want to filter out the employees who are younger than 30 years old.

The filter() function takes a lambda function as its first argument, which defines the filtering condition. In this case, the lambda function checks if the age of each employee is less than 30. The second argument of the filter() function is the actual list of employees from the JSON data.

The filtered results are stored in the filtered_data list, which can be printed using the json.dumps() function with indentation for better readability.

Output:


[
  {
    "name": "Mike",
    "age": 28,
    "department": "Finance"
  }
]
  

As shown in the output, the employee named "Mike" with an age of 28 is the only result that satisfies the filtering condition.

This example demonstrates how to filter nested JSON data based on a specific criteria using Python. You can modify the lambda function inside the filter() function to apply different filtering conditions as per your requirements.

Leave a comment