Skip to content

Python iterate over JSON array

  • by

Python iterate over JSON array is process of looping or iterating over an array within a JSON (JavaScript Object Notation) data structure using Python programming language. JSON arrays are denoted by square brackets [ ] and can contain multiple elements, such as objects, strings, numbers, or nested arrays.

To iterate over a JSON array in Python, you can use the json module to parse the JSON data into a Python object, and then loop through the resulting list or array.

Here’s the syntax for iterating over a JSON array in Python:

import json

# Example JSON array
json_data = '[{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}, {"name": "Charlie", "age": 35}]'

# Parse JSON array into a Python object
data = json.loads(json_data)

# Iterate over the array
for item in data:
    # Access properties of each object
    name = item['name']
    age = item['age']
    
    # Do something with the data
    # ...
  1. Import the json module to work with JSON data.
  2. Define your JSON array in a string format, as json_data.
  3. Use json.loads() to parse the JSON string into a Python object. Assign the result to the variable data.
  4. Use a for loop to iterate over the elements of the JSON array. Each item represents an object within the array.
  5. Access the properties of each object using the appropriate keys, such as item['name'] or item['age'].
  6. Perform any desired operations or actions using the data obtained from the JSON array.

Python iterates over JSON array example

Simple example code.

import json

# Example JSON array
json_data = '''
[
    {
        "name": "Alice",
        "age": 25,
        "city": "New York"
    },
    {
        "name": "Bob",
        "age": 30,
        "city": "Los Angeles"
    },
    {
        "name": "Charlie",
        "age": 35,
        "city": "Chicago"
    }
]
'''

# Parse JSON array into a Python object
data = json.loads(json_data)

# Iterate over the array
for item in data:
    name = item['name']
    age = item['age']
    city = item['city']
    
    print(f"Name: {name}, Age: {age}, City: {city}")

Output:

Python iterate over JSON array

By iterating over a JSON array, you can perform various operations on each element, such as extracting specific properties, manipulating the data, or performing calculations.

Comment if you have any doubts or suggestions on this Python iteration topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading