Looping through JSON in Python refers to the process of iterating over the elements of a JSON array or the key-value pairs of a JSON object. It involves converting the JSON data into a Python object (such as a list or a dictionary) using the json
module, and then using loops to traverse and process the JSON data.
Here’s the syntax for looping through JSON data in Python:
import json
# JSON data
json_data = '{"name": "John", "age": 30, "city": "New York"}'
# Parse the JSON string into a Python object
data = json.loads(json_data)
# Loop through each key in the JSON object
for key in data:
# Access the value using the key
value = data[key]
# Do something with the key-value pair
print(key, ":", value)
You can replace the print
statement with any desired actions or processing logic based on your specific use case.
Loop through JSON Python example
Simple example code.
import json
# Sample JSON object
json_data = '''
{
"name": "John",
"age": 30,
"city": "New York",
"pets": ["dog", "cat"]
}
'''
# Parse the JSON string into a Python object
data = json.loads(json_data)
# Loop through each key-value pair in the JSON object
for key, value in data.items():
# Do something with the key-value pair
print(key, ":", value)
Output:
In this example, we start by importing the json
module. Then, we define a JSON object as a string in the json_data
variable.
We use json.loads()
to parse the JSON string into a Python object, which is stored in the data
variable. This object becomes a dictionary in this case.
We then iterate over each key-value pair in the data
dictionary using a for
loop. The items()
method returns a list of tuples, where each tuple represents a key-value pair in the dictionary.
Inside the loop, we access the key and value of each pair using the variables key
and value
, respectively.
Do comment if you have any doubts or suggestions on this Python JSON topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.