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
json_string = json.dumps(list)
We have to import json package to use json.dumps().
Examples
In the following examples, we take a list of elements, and convert this list to a JSON string using json.dumps().
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
a_list = [41, 58, 63]
json_string = json.dumps(a_list)
print(json_string)
Output
[41, 58, 63]
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
a_list = [{'a':1, 'b':2}, {'c':3, 'd':4}]
json_string = json.dumps(a_list)
print(json_string)
Output
[{"a": 1, "b": 2}, {"c": 3, "d": 4}]
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
a_list = [[{'a':1, 'b':2}], [{'c':3, 'd':4}]]
json_string = json.dumps(a_list)
print(json_string)
Output
[[{"a": 1, "b": 2}], [{"c": 3, "d": 4}]]
Video
In the following YouTube video, a step by step process and examples are given to show how to convert a Python list into a JSON string.
Summary
In this Python JSON Tutorial, we learned how to convert a Python List into JSON string.