How to loop through JSON with subkeys in Python

In this tutorial, we will learn how to loop through JSON with subkeys in Python. JSON (JavaScript Object Notation) is a popular and special type of data format used for data manipulation.

First of all, we will see how to loop through keys and then we will see how to loop through subkeys also. So, let’s start…

Iterate through JSON with keys in Python

Let’s consider the following JSON file and save it as ‘json_multidimensional.json’

{"website":"codespeedy","topic":"json and python","no_of_posts":{"year2019":15,"year2020":5}}

To iterate through JSON with keys, we have to first import the JSON module and parse the JSON file using the ‘load’ method as shown below.

import json
with open('json_multidimensional.json','r') as string:
    my_dict=json.load(string)
string.close()

It will parse the ‘json_multidimensional.json’ file as the dictionary ‘my_dict’.

Now to iterate with keys, see the below code.

import json
with open('json_multidimensional.json','r') as string:
    my_dict=json.load(string)
string.close()

for k in my_dict:
    print("key:"+k+", value:"+str(my_dict[k]))

Output:

key:website, value:codespeedy
key:topic, value:json and python
key:no_of_posts, value:{'year2019': 15, 'year2020': 5}

We can do the same thing in a little different way like this.

import json
with open('json_multidimensional.json','r') as string:
    my_dict=json.load(string)
string.close()

for k,v in my_dict.items():
    print("key:"+k+", value:"+str(v))

Output:

key:website, value:codespeedy
key:topic, value:json and python
key:no_of_posts, value:{'year2019': 15, 'year2020': 5}

We have seen that the output is the same as the previous one.

Now we will see how to iterate with subkeys in a multidimensional dictionary.

Iterate through JSON with keys: Recursive way

We can do it in a recursive way. See the following code.

import json
with open('json_multidimensional.json','r') as string:
    my_dict=json.load(string)
string.close()

def iterate_multidimensional(my_dict):
    for k,v in my_dict.items():
        if(isinstance(v,dict)):
            print(k+":")
            iterate_multidimensional(v)
            continue
        print(k+" : "+str(v))

iterate_multidimensional(my_dict)

Output:

website : codespeedy
topic : json and python
no_of_posts:
year2019 : 15
year2020 : 5

In the above code, we have defined a function which iterates with the keys and if the value is again a dictionary then it will call the function itself in a recursive way and iterate through the subdictionary. In this way, we can loop through JSON with subkeys in Python.

You may also read,

2 responses to “How to loop through JSON with subkeys in Python”

  1. Disha says:

    {
    “note”:”This file contains the actual data for your assignment”,
    “comments”:[
    {
    “name”:”Sukhpal”,
    “count”:97
    },
    {
    “name”:”Nadisa”,
    “count”:95
    }
    ]
    }

    i have this JSON data. so i got an error that “i need to use tuple”. please give me solution for this.

    • Bikram Mondal says:

      Hi Disha, it is giving the output like this-
      key:note, value:This file contains the actual data for your assignment
      key:comments, value:[{‘name’: ‘Sukhpal’, ‘count’: 97}, {‘name’: ‘Nadisa’, ‘count’: 95}]

      N.B: In the json file you should use the “–” (double quote) correctly.

Leave a Reply

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