# How do I loop through a JSON file with multiple keys/sub-keys in Python?

PythonProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −

{
"id": "file",
"value": "File",
"popup": {
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}

## Example

You can load it in your python program and loop over its keys in the following way −

import json
f = open('data.json')
f.close()

# Now you can use data as a normal dict −

for (k, v) in data.items():
print("Key: " + k)
print("Value: " + str(v))

## Output

This will give the output −

Key: id
Value: file
Key: value
Value: File
Key: popup
Value: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}

If you want to iterate over sub values as well, you'd have to write a recursive function that can iterate over this tree-like dict.

Updated on 05-Mar-2020 08:14:19