Loop through a JSON array in Python

First, we will understand the JSON array and then loop through it in Python.

So what is a JSON array? A JSON array is the Python list of key: value pair which is ordered in nature. So JSON array is just a Python dictionary containing an ordered list of key: value pair. JSON array can be any data type. It can store String, Integer, and other data types as well.

A JSON array is also indexed which means we can access the data inside the array by using an index value. A JSON array is enclosed in [] square brackets and values inside the array are separated by comma(,).

Also read: How to loop through JSON with subkeys in Python

Creating JSON Array and Object

We can create JSON Array and Objects from the Python list and dictionary. For creating a JSON array of strings we can use curly brackets{} with single quotes as shown in the below Python code.

And for making a JSON object we can use the “json.loads()” function in the Python after importing the “json” library into the Python program also shown in the following Python code below.

Looping through a JSON array

We use For Loop function to iterate through a JSON array after creating it. We first, import the json library by using the import function and then create a function using def keyword.

After initializing the function we create a JSON array by using a single quote with curly brackets{}. We then provide the key: value pair to it. After creating a JSON array we then convert it into JSON objects using the json.loads() function.

Now, JSON array has been created and we can use traditional For Loop to loop inside the JSON array and print it’s either key or value or we can also print (key: value pair) both.

Refer to the below Python code to loop through a JSON array:

import json

def main():

    # creating JSON array
    j_String = '{"Gaurav":"Pro-Coder","Car":"Ferrari","Home":"Seattle"}'

    # changing JSON string into a JSON object
    j_Object = json.loads(j_String)

    # printing keys and values
    for i in j_Object:
        value = j_Object[i]
        print("Key and Value pair are ({}) = ({})".format(i, value))

    pass

if __name__ == '__main__':
    main()

Output:

Key and Value pair are (Gaurav) = (Pro-Coder)
Key and Value pair are (Car) = (Ferrari)
Key and Value pair are (Home) = (Seattle)

You can also refer to this link Python JSON Encoder and Decoder for more understanding of JSON encoding and decoding in Python.

Leave a Reply

Your email address will not be published.