Python List to JSON

Python List to JSON

Python List to JSON

To convert a Python List to JSON, use json.dumps() function. dumps() function takes list as argument and returns a JSON String.

Syntax

The syntax to use json.dumps() method is

import json

jsonString = json.dumps(list)

We have to import json package to use json.dumps().

Example 1: Convert Python List to JSON

In this example, we will take a Python list with some numbers in it and convert it to JSON string.

Python Program

import json

aList = [41, 58, 63]
jsonStr = json.dumps(aList)
print(jsonStr)
Run this program ONLINE

Output

[41, 58, 63]

Example 2: Convert Python List of Dictionaries to JSON

In this example, we will take a Python List with Dictionaries as elements and convert it to JSON string.

Python Program

import json

aList = [{'a':1, 'b':2}, {'c':3, 'd':4}]
jsonStr = json.dumps(aList)
print(jsonStr)
Run this program ONLINE

Output

[{"a": 1, "b": 2}, {"c": 3, "d": 4}]

Example 3: Convert Python List of Lists to JSON

In this example, we will take a Python List of Lists and convert it to JSON string.

Python Program

import json

aList = [[{'a':1, 'b':2}], [{'c':3, 'd':4}]]
jsonStr = json.dumps(aList)
print(jsonStr)
Run this program ONLINE

Output

[[{"a": 1, "b": 2}], [{"c": 3, "d": 4}]]

Summary

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