Contents
- Introduction
- Syntax
- Example 1: Convert Python List to JSON
- Example 2: Convert Python List of Dictionaries to JSON
- Example 3: Convert Python List of Lists to JSON
- Summary
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]RunOutput
[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]RunOutput
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]RunOutput
[[{"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.
Related Tutorials
- Python JSON to Dictionary
- Python Parse JSON String
- Python Dictionary to JSON
- Python CSV to JSON
- Python JSON to List
- Python Create JSON
- Python Write JSON to File
- Python Read JSON File