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
# 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)
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
# 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)
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
# 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}")
OutputThe 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)
Output[{'name': 'Mouse', 'price': 20, 'stock': 10}]
Similar Reads
Filter List Of Dictionaries in Python Filtering a list of dictionaries is a fundamental programming task that involves selecting specific elements from a collection of dictionaries based on defined criteria. This process is commonly used for data manipulation and extraction, allowing developers to efficiently work with structured data b
2 min read
Unique Dictionary Filter in List - Python We are given a dictionary in list we need to find unique dictionary. For example, a = [ {"a": 1, "b": 2}, {"a": 1, "b": 2}, {"c": 3}, {"a": 1, "b": 3}] so that output should be [{'a': 1, 'b': 2}, {'a': 1, 'b': 3}, {'c': 3}].Using set with frozensetUsing set with frozenset, we convert dictionary item
3 min read
Build a Json Object in Python JSON (JavaScript Object Notation) is a lightweight data-interchange format widely used for data exchange between a server and a web application, as well as between different components of a system. In Python, working with JSON is straightforward, and the built-in json module provides functions to en
2 min read
Add Json Library in Python Python JSON library is part of the Python standard library, installing it in Python doesn't require installing any other packages. It is a quick and easy process, allowing you to seamlessly work with common data formats. In this article, we will see how to add and use JSON library in Python. Add and
2 min read
Python | Filter Tuple Dictionary Keys Sometimes, while working with Python dictionaries, we can have itâs keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get filtered tuple key elements, we need to perform certain functi
4 min read
Python - Non K distant elements Given a list, the task is to write a Python program to extract all the elements such that no element is at K distant from one other. Examples: Input : test_list = [8, 10, 16, 20, 3, 1, 7], K = 2 Output : [16, 20, 7] Explanation : 16 + 2 = 18, 16 - 2 = 14, both are not in list, hence filtered. Input
2 min read
Filter List of Python Dictionaries by Key in Python In Python, filtering a list of dictionaries based on a specific key is a common task when working with structured data. In this article, weâll explore different ways to filter a list of dictionaries by key from the most efficient to the least.Using List Comprehension List comprehension is a concise
3 min read
Return Data in JSON Format Using FastAPI in Python FastAPI is a modern, fast, web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be easy to use and efficient, providing automatic generation of OpenAPI and JSON Schema documentation. In this article, we will see how to return data in JSON format usi
2 min read
Get a Subset of Dict in Python In Python, dictionaries store key-value pairs and are pivotal in data management. Extracting dictionary subsets based on specific criteria is key for targeted data analysis, ensuring operational efficiency by focusing on relevant data. This technique, vital in data processing and machine learning, a
3 min read
Python - Filter Tuples with Integers Given Tuple list, filter tuples which are having just int data type. Input : [(4, 5, "GFg"), (3, ), ("Gfg", )] Output : [(3, )] Explanation : 1 tuple (3, ) with all integral values. Input : [(4, 5, "GFg"), (3, "Best" ), ("Gfg", )] Output : [] Explanation : No tuple with all integers. Method #1 : Usi
5 min read