To convert a Python List to JSON, use json.dumps() function. dumps() function takes list as argument and returns a JSON String. Show SyntaxThe 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 JSONIn 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 JSONIn 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 [{"a": 1, "b": 2}, {"c": 3, "d": 4}]Example 3: Convert Python List of Lists to JSONIn 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}]]SummaryIn this tutorial of Python Examples, we learned how to convert a Python List into JSON string. |