Convert Python list to JSON | Example code

Use json.dumps() function to convert list to JSON in Python. This function takes a list as an argument and returns a JSON String.

Syntax

import json

jsonString = json.dumps(list)

Python list to JSON example

Simple example code takes a Python list with some numbers in it and converts it to a JSON string.

import json

aList = [1, 2, 3]
res = json.dumps(aList)

print(res)
print(type(res))

Output:

Convert Python list to JSON

How to Convert Python List of Dictionaries to JSON?

Answer: Same method son.dumps() will work for converting list fo dict into a JSON.

import json

aList = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]
res = json.dumps(aList)

print(res)

Output: [{“a”: 1, “b”: 2}, {“c”: 3, “d”: 4}]

Convert Python List of Lists to JSON

You can convert the list into JSON using the dumps() method. First import the json module then use the method.

import json

aList = [[{'a': 1, 'b': 2}], [{'c': 3, 'd': 4}]]
res = json.dumps(aList)

print(res)

Output: [[{“a”: 1, “b”: 2}], [{“c”: 3, “d”: 4}]]

Do comment if you have any doubts and suggestions on this Python List tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.