Convert a List to JSON in Python

  • Post category:List

Converting a list to JSON format in Python can be achieved using the json module. Here are two examples:

Example 1:

import json

fruits = ['apple', 'banana', 'orange']
json_data = json.dumps(fruits)
print(f"JSON representation: {json_data}")

Output:

JSON representation: [“apple”, “banana”, “orange”]

Example 2:

import json

numbers = [1, 2, 3, 4, 5]
json_data = json.dumps(numbers)
print(f"JSON representation: {json_data}")

Output:

JSON representation: [1, 2, 3, 4, 5]