You can use a for loop to iterate over the elements in a JSON object. However, it’s important to note that JSON objects are represented as dictionaries in Python. Here’s an example of how you can use a for loop to iterate over a JSON object using the json
module in Python:
import json
# Assuming you have a JSON object as a string
json_str = '{"name": "John", "age": 30, "city": "New York"}'
# Parse the JSON string into a Python dictionary
json_obj = json.loads(json_str)
# Iterate over the key-value pairs in the dictionary
for key, value in json_obj.items():
print(key, value)
Code language: Python (python)
Output:
name John
age 30
city New York
Code language: Python (python)
In this example, we use the json.loads()
function to parse the JSON string into a Python dictionary. Then, we use a for loop to iterate over the items of the dictionary. The items()
method returns a sequence of key-value pairs, allowing us to access both the key and value within the loop.
You can perform any desired operations within the loop based on the specific structure of your JSON object.
How to create JSON array in Python?
In Python, you can create a JSON array by using a list and then converting it to a JSON string using the json
module. Here’s an example:
import json
# Create a list to represent the JSON array
data = ["apple", "banana", "orange"]
# Convert the list to a JSON string
json_str = json.dumps(data)
# Print the JSON string
print(json_str)
Code language: Python (python)
Output:
["apple", "banana", "orange"]
Code language: Python (python)
In this example, we create a Python list called data
with three elements: “apple”, “banana”, and “orange”. We then use the json.dumps()
function to convert the list to a JSON string. The resulting JSON string represents a JSON array.
You can add or modify the elements in the list to suit your specific requirements, and the resulting JSON string will reflect the changes.
Read More;
- What is TQDM in for loop Python?
- What is an example of a syntax error in Python?
- What is the dash function in Python?
- How to test a class with unittest Python?
- What is an example of a runtime error?
- How to run Python script from GitLab?
- What is an example of a string in Python?
- What is RegEx in Python with example?
- What is an example of a Boolean in Python?
- What is an example of built-in and user-defined functions in Python?
- What is an example of a constructor in Python?
- What is a dictionary in Python example?