Python How to Convert JSON to List Easily
Use
json.loads(json_string) to convert a JSON string representing a list into a Python list.Examples
Input"[1, 2, 3]"
Output[1, 2, 3]
Input"[\"apple\", \"banana\", \"cherry\"]"
Output["apple", "banana", "cherry"]
Input"[]"
Output[]
How to Think About It
To convert JSON to a list, first understand that JSON is a string format. You need to parse this string into Python objects. If the JSON string represents a list, parsing it will give you a Python list.
Algorithm
1
Get the JSON string input.2
Use a JSON parsing function to convert the string to a Python object.3
Return the Python list obtained from parsing.Code
python
import json json_string = '["apple", "banana", "cherry"]' python_list = json.loads(json_string) print(python_list)
Output
['apple', 'banana', 'cherry']
Dry Run
Let's trace converting '["apple", "banana", "cherry"]' to a Python list.
1
Input JSON string
'["apple", "banana", "cherry"]'
2
Parse JSON string
json.loads('["apple", "banana", "cherry"]')
3
Output Python list
['apple', 'banana', 'cherry']
| Step | Action | Value |
|---|---|---|
| 1 | Input JSON string | ["apple", "banana", "cherry"] |
| 2 | Parse JSON string | ['apple', 'banana', 'cherry'] |
| 3 | Output Python list | ['apple', 'banana', 'cherry'] |
Why This Works
Step 1: JSON is a string format
The input is a string that looks like a list but is actually text.
Step 2: Use json.loads to parse
The json.loads function reads the string and converts it into Python objects.
Step 3: Result is a Python list
If the JSON string represents a list, the result is a Python list you can use in your code.
Alternative Approaches
Using ast.literal_eval
python
import ast json_string = '[1, 2, 3]' python_list = ast.literal_eval(json_string) print(python_list)
This works if the JSON is simple and safe, but json.loads is preferred for strict JSON parsing.
Manual parsing (not recommended)
python
json_string = '[1, 2, 3]' python_list = json_string.strip('[]').split(', ') print(python_list)
This is fragile and only works for very simple lists of strings or numbers.
Complexity: O(n) time, O(n) space
Time Complexity
Parsing the JSON string takes time proportional to its length, so it's O(n).
Space Complexity
The parsed list uses extra memory proportional to the size of the JSON string, so O(n).
Which Approach is Fastest?
Using json.loads is efficient and safe; alternatives like ast.literal_eval are slower and less strict.
| Approach | Time | Space | Best For |
|---|---|---|---|
| json.loads | O(n) | O(n) | Standard JSON parsing, safe and fast |
| ast.literal_eval | O(n) | O(n) | Simple Python literals, less strict |
| Manual parsing | O(n) | O(n) | Very simple cases, fragile |
Always use
json.loads to safely convert JSON strings to Python lists.Trying to use
json.load on a string instead of a file causes errors.