Python JSON to List

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.

Example 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'])
Run this program ONLINE

Output

2

Example 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])
Run this program ONLINE

Output

{'a': 1, 'b': 2}

Summary

In this tutorial of Python Examples, we learned how to load a JSON Array string to Python List.