Loop through a JSON array in Python

In this tutorial, I will write a simple program to show you how to loop through a JSON array in Python.

In order to do that, what we need is a sample JSON array. We will loop through that JSON array and print the data.

[
  {
    "language": "Java",
    "duration": 30,
    "author": "saruque",
    "site": "codespeedy"
  },
  {
    "language": "Swift",
    "duration": 50,
    "author": "faruque",
    "site": "swiftspeedy"
  },
  {
    "language": "Python",
    "duration": 50,
    "author": "Parvez",
    "site": "codespeedy"
  }
]

We are taking this sample JSON for our example.

We have some keys and values in this JSON array.

The module we need to import is json.

Python program to loop through a JSON array

import json
myJSON_array = [
  {
    "language": "Java",
    "duration": 30,
    "author": "saruque",
    "site": "codespeedy"
  },
  {
    "language": "Swift",
    "duration": 50,
    "author": "faruque",
    "site": "swiftspeedy"
  },
  {
    "language": "Python",
    "duration": 50,
    "author": "Parvez",
    "site": "codespeedy"
  }
]

for data in myJSON_array:
    print("language:", data["language"])
    print("duration:", data["duration"])
    print("author:", data["author"])
    print("site:", data["site"])



Output:

language: Java
duration: 30
author: saruque
site: codespeedy
language: Swift
duration: 50
author: faruque
site: swiftspeedy
language: Python
duration: 50
author: Parvez
site: codespeedy

If you want a separator after iterating each loop you can use print("---") at the end of the loop. Something like this will help you to read where your data ends in a single iteration.

for data in myJSON_array:
    print("language:", data["language"])
    print("duration:", data["duration"])
    print("author:", data["author"])
    print("site:", data["site"])
    print("---")

Loop through a JSON array from a separate file

Now let’s assume that the same JSON array is stored in a separate file sample_json.json. The file type is .json.

You can simply put the file path in the first argument of with open().

So how to iterate through a JSON file?

import json
with open('sample_json.json', 'r') as json_file:
    myJSON_array = json.load(json_file)

for data in myJSON_array:
    print("language:", data["language"])
    print("duration:", data["duration"])
    print("author:", data["author"])
    print("site:", data["site"])
    print("---")

The output will be the same.

Leave a Reply

Your email address will not be published. Required fields are marked *