Python JSON to List
Python JSON to List
To convert a JSON String to Python List, use json.loads() function. loads() function takes JSON Array string as argument and returns a Python List.
Syntax
The syntax to use json.loads() method is
import json
aList = json.dumps(jsonString)
We have to import json package to use json.dumps() function.
Note: Please note that dumps() function returns a Python List, only if the JSON string is a JSON Array.
Examples
1. Convert JSON array string to Python list
In this example, we will take a JSON Array string and convert it into Python List. The JSON Array has two elements, with each element containing two key:value pairs of each.
After loading the JSON string to list, we shall print the value for key "b".
Python Program
import json
jsonStr = '[{"a":1, "b":2}, {"c":3, "d":4}]'
aList = json.loads(jsonStr)
print(aList[0]['b'])
Output
2
2. Convert JSON array of arrays string to Python list
In this example, we will take a JSON String with Array of Arrays and convert it to Python List of Lists.
After parsing the JSON string to Python List, we shall access the first element of first first in the whole list.
Python Program
import json
jsonStr = '[[{"a":1, "b":2}], [{"c":3, "d":4}]]'
aList = json.loads(jsonStr)
print(aList[0][0])
Output
{'a': 1, 'b': 2}
Summary
In this Python JSON Tutorial, we learned how to load a JSON Array string to Python List.