Python JSON Data Filtering
Last Updated :
22 Feb, 2024
JSON (JavaScript Object Notation) is a lightweight data-interchange format widely used for storing and exchanging data between a server and a web application. Python, with its built-in json module, provides powerful tools for working with JSON data. In this article, we’ll explore how to filter and manipulate JSON data using Python, focusing on five commonly encountered scenarios.
Python JSON Data Filtering
Below, are the methods of Python JSON Data Filtering in Python.
JSON Data Filtering by Key
In this example, the below code uses the `JSON` module in Python to load a JSON-formatted string representing personal data. It then filters the data by selecting only the “name” and “age” keys, creating a new dictionary called `filtered_data`, and printing the result.
Python3
import json
person_data = '{"name": "John", "age": 30, "city": "New York", "occupation": "Engineer"}'
person = json.loads(person_data)
filtered_data = {key: person[key] for key in [ "name" , "age" ]}
print (filtered_data)
|
Output
{'name': 'John', 'age': 30}
JSON Data Filtering by Value
In this example, the below code utilizes Python’s `json` module to load a JSON array representing people’s data. It then filters the array to retain only those individuals whose age is greater than 30, creating a new list called `filtered_people.
Python3
import json
people_data = '[{"name": "John", "age": 30}, {"name": "Alice", "age": 25}, {"name": "Bob", "age": 35}]'
people = json.loads(people_data)
filtered_people = [person for person in people if person[ "age" ] > 30 ]
print (filtered_people)
|
Output
[{'name': 'Bob', 'age': 35}]
JSON Data Filtering Using Nested JSON
In this example, the below code employs Python’s `json` module to load a nested JSON object representing book data. It then filters the nested structure to extract the author’s age and prints the result.
Python3
import json
book_data = '{"title": "The Python Guide", "author": {"name": "Jane Doe", "age": 40}}'
book = json.loads(book_data)
author_age = book[ "author" ][ "age" ]
print (f "The author's age is {author_age}" )
|
Output
The author's age is 40
JSON Data Filtering Using Conditional Filtering
In this example, in below code `json` module is used to load a JSON array containing product information. The code then performs conditional filtering to create a new list, `in_stock_products`, including only those products with stock quantities greater than 5.
Python3
import json
products_data = '[{"name": "Laptop", "price": 1200, "stock": 5}, {"name": "Headphones", "price": 80, "stock": 0}, {"name": "Mouse", "price": 20, "stock": 10}]'
products = json.loads(products_data)
in_stock_products = [product for product in products if product[ "stock" ] > 5 ]
print (in_stock_products)
|
Output
[{'name': 'Mouse', 'price': 20, 'stock': 10}]
Share your thoughts in the comments
Please Login to comment...