Loop through a JSON array in Python
Last Updated :
28 Mar, 2024
A JSON array is an ordered list of values that can store multiple values such as string, number, boolean, or object. The values in a JSON array must be separated by commas and enclosed in squares in brackets []. In this article, we will learn how we can loop through a JSON array in Python.
Iterate over a JSON object in Python
Arrays in JSON are almost the same as arrays in Python. The array index begins with 0 and each value is separated by a comma. JSON arrays can be of multiple data types that is, they can store a string, number, boolean, or even a whole JSON array. Here are some of the benefits of using JSON arrays:
- They are easy to read and write.
- They are human-readable and machine-readable.
- They are a standard format that is supported by many languages and platforms.
- They are efficient in terms of space and bandwidth.
So, while working with data, JSON arrays are found to be a powerful tool that can help you to store and organize the data in a structured way. Here is an example of a JSON array:
[
"string",
123,
567.36,
true,
[
"Array",
"In",
"Array"
],
{
"name": "John Doe"
}
]
Looping through a JSON Array in Python
You can loop through a JSON array in Python by using the json module and then iterating through the array using a for loop. Let us see a few examples.
Loop Through JSON data as a String
In this example, we will define the JSON data as a string and load it using the and the load() function to convert the JSON data to a Python object. Then using a for loop we will iterate through the array.
Python3
import json
# Sample JSON data
json_data = """
[
{"id": 1, "name": "John"},
{"id": 2, "name": "Jane"},
{"id": 3, "name": "Bob"}
]
"""
# Convert JSON data to a Python object
data = json.loads(json_data)
# Iterate through the JSON array
for item in data:
print(item["id"], item["name"])
Output:
1 John
2 Jane
3 Bob
Looping JSON data as an Array
In the same way as above, we can also loop through an array that is being present as a value for a key in a JSON/Dict, we have to only make some of the minor changes as follows:
Python3
import json
# Sample JSON data
json_data = """
{
"sample_data": [
{"id": 1, "name": "John"},
{"id": 2, "name": "Jane"},
{"id": 3, "name": "Bob"}
]
}
"""
# Convert JSON data to a Python object
data = json.loads(json_data)
# Iterate through the array
for item in data["sample_data"]:
# Updated data["sample_data"] as the array is
# being present as the value for sample_data
print(item["id"], item["name"])
Output:
1 John
2 Jane
3 Bob
Looping JSON data as a JSON file
In this example, we will be looping through a JSON array whose data is being stored in a JSON file named data.json. Here is the content of the data.json file:
[
{"id": 1, "name": "John"},
{"id": 2, "name": "Jane"},
{"id": 3, "name": "Bob"}
]
Python3
import json
# Load the JSON data
with open("data.json") as f:
data = json.load(f)
# Iterate through the JSON array
for item in data:
print(item["id"], item["name"])
Output:
1 John
2 Jane
3 Bob
Looping JSON data as a Nested JSON Array
In this example, we will be looping through a Nested JSON array. We will go through two loop, the first loop iterates through the main Array while the inner loop iterates through the Array present as the value of nested_array key and prints the value.
Python3
data = [
{
"nested_array": [
{
"value": "1"
},
{
"value": "2"
},
{
"value": "3"
}
]
},
{
"nested_array": [
{
"value": "4"
},
{
"value": "5"
},
{
"value": "6"
}
]
}
]
for item in data:
for subitem in item["nested_array"]:
print(subitem["value"])
Output:
1
2
3
4
5
6
You can refer to this article for more information regarding JSON files in Python: Python JSON
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow. Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
11 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
10 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list(). Let's look at a simple exa
3 min read