
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How do I loop through a JSON file with multiple keys/sub-keys in Python?
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": { "menuitem": [ {"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') data = json.load(f) 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.
- Related Articles
- Python dictionary with keys having multiple inputs
- MongoDB aggregation with multiple keys
- Python - Intersect two dictionaries through keys
- How can I handle multiple keyboard keys using Selenium Webdriver?
- How to efficiently perform “distinct” with multiple keys in MongoDB?
- Compare keys & values in a JSON object when one object has extra keys in JavaScript
- How do I see all foreign keys to a table column?
- Check if given multiple keys exist in a dictionary in Python
- What are private keys and public keys? How do they work?
- How do you Loop Through a Dictionary in Python?
- How to loop through multiple lists using Python?
- How to create Python dictionary with duplicate keys?
- How to parse a JSON without duplicate keys using Gson in Java?
- Keys associated with Values in Dictionary in Python
- How to split Python dictionary into multiple keys, dividing the values equally?

Advertisements