How to Extract Keys and Values from a JSON Array Object in Python?

Estimated read time 2 min read

To extract keys and values from a JSON array object in Python, you can use the json module, which is included in the Python standard library. Here’s an example:

import json

# Input JSON array
json_str = '[{"key1": "value1", "key2": "value2"}, {"key3": "value3", "key4": "value4"}]'

# Load JSON data
json_data = json.loads(json_str)

# Iterate through each object in the JSON array
for obj in json_data:
    # Extract keys and values from the object
    for key, value in obj.items():
        print(f"Key: {key}, Value: {value}")

In this example, we first define an input JSON array as a string json_str. Then, we use the json.loads() function from the json module to parse the JSON data into a Python object. In this case, the JSON data is an array of objects, and we get a list of dictionaries in json_data. Next, we use a nested loop to iterate through each object in the JSON array. Inside the loop, we use the items() method on the dictionary object to extract the keys and values as key-value pairs. We then print the extracted keys and values using a print() statement, but you can also store them in variables or use them for further processing as needed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply