Python Convert JSON to List

1. Introduction

JSON (JavaScript Object Notation) is a standard data-interchange format that is easy for humans to read and write. In Python, JSON is commonly converted into dictionaries for easier access and manipulation. However, when the JSON structure starts with a JSON array, you might need to convert it directly into a Python list. This blog post will walk you through converting a JSON array to a Python list.

Definition

Converting JSON to a list in Python involves parsing a JSON formatted string that represents an array and creating a Python list with the same elements. The Python json module provides the loads() function for this purpose, which can interpret a JSON string and return corresponding Python data types.

2. Program Steps

1. Import the json module.

2. Have a JSON string formatted as an array.

3. Parse the JSON string into a Python list using the json.loads() function.

4. Use the resulting list in your Python code as needed.

3. Code Program

# Step 1: Import the json module
import json

# Step 2: Define a JSON string that is an array
json_array_str = '["apple", "banana", "cherry"]'

# Step 3: Parse the JSON string into a Python list
resulting_list = json.loads(json_array_str)

# Step 4: Print the resulting list
print(resulting_list)

Output:

['apple', 'banana', 'cherry']

Explanation:

1. The json module, which includes functions for parsing JSON strings, is imported.

2. json_array_str holds a JSON array as a string, which contains a list of fruit names.

3. resulting_list is a Python list created from json_array_str by using the json.loads() function, which converts the JSON array into a Python list.

4. The print() function is used to display resulting_list, confirming that the JSON string has been successfully converted into a Python list with the same elements.


Comments