Python JSON Data Filtering
- Filtering by Key
- Filtering by Value
- Nested JSON Filtering
- Conditional Filering
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 # Sample JSON data person_data = '{"name": "John", "age": 30, "city": "New York", "occupation": "Engineer"}' person = json.loads(person_data) # Filtering by key filtered_data = {key: person[key] for key in [ "name" , "age" ]} print (filtered_data) |
{'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 # Sample JSON array people_data = '[{"name": "John", "age": 30}, {"name": "Alice", "age": 25}, {"name": "Bob", "age": 35}]' people = json.loads(people_data) # Filtering by value filtered_people = [person for person in people if person[ "age" ] > 30 ] print (filtered_people) |
[{'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 # Sample nested JSON data book_data = '{"title": "The Python Guide", "author": {"name": "Jane Doe", "age": 40}}' book = json.loads(book_data) # Nested JSON filtering author_age = book[ "author" ][ "age" ] print (f "The author's age is {author_age}" ) |
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 # Sample JSON array of products 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) # Conditional filtering in_stock_products = [product for product in products if product[ "stock" ] > 5 ] print (in_stock_products) |
[{'name': 'Mouse', 'price': 20, 'stock': 10}]
Python JSON Data Filtering
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.