How to Loop Through a JSON Object in Python?

Estimated read time 2 min read

In Python, you can loop through a JSON object using a for loop. Here’s an example:

import json

# JSON object
data = {
    "name": "John",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "New York",
        "state": "NY",
        "zip": "10001"
    }
}

# Loop through the JSON object
for key, value in data.items():
    print("Key:", key)
    print("Value:", value)

In the above example, we have a JSON object data with multiple key-value pairs. We use a for loop to iterate over the items in the JSON object using the items() method, which returns a list of key-value pairs as tuples. Inside the loop, we can access the key and value of each item using the variables key and value, respectively.

You can perform various operations on the key and value inside the loop, such as printing them, manipulating them, or storing them in another data structure. Note that the order of items in a JSON object is not guaranteed, as JSON is a collection of key-value pairs and does not have a defined order. If you need to preserve the order of items, you can use the collections.OrderedDict class from the Python standard library or a third-party library that supports ordered dictionaries.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply