How to Parse a JSON Array in Python

AuthorSumit Dey Sarkar

Pubish Date30 Apr 2023

categoryPython

In this tutorial we will learn how to parse a JSON array in Python.

 

How to Parse a JSON Array in Python

 

How to parse a JSON array in Python

The json module, which is a component of Python's standard library, can be used to parse a JSON array in Python.

 

An example of how to parse a JSON array in Python is given here:

import json

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

# Parse JSON array
data = json.loads(json_array)

# Loop through each object in the array and print the name and age
for obj in data:
    print("Name:", obj["name"])
    print("Age:", obj["age"])

 

In this example, we first import the json module. We then define an example JSON array as a string.

 

After that, the JSON array is converted into a Python object using the json.loads() method. Each dictionary in the resulting object serves as a representation of a different object from the original JSON array.

 

The name and age values for each object are then printed out by iterating through each dictionary in the list.

 

It should be noted that the json.load() method can be used to parse JSON directly from a file if the JSON array is kept in a file.

 

Comments 0

Leave a comment