Python How to Convert List to JSON String
json.dumps() function from Python's json module to convert a list to a JSON string, like json.dumps(your_list).Examples
How to Think About It
json.dumps() function. This string can then be saved or sent to other programs.Algorithm
Code
import json my_list = ["apple", "banana", "cherry"] json_string = json.dumps(my_list) print(json_string)
Dry Run
Let's trace converting ['apple', 'banana', 'cherry'] to JSON string.
Import json module
json module is ready to use.
Define list
my_list = ['apple', 'banana', 'cherry']
Convert list to JSON string
json_string = json.dumps(my_list) results in '["apple", "banana", "cherry"]'
| Step | Action | Value |
|---|---|---|
| 1 | Import json | json module ready |
| 2 | Define list | ['apple', 'banana', 'cherry'] |
| 3 | Convert to JSON | ["apple", "banana", "cherry"] |
Why This Works
Step 1: Import json module
The json module provides tools to convert Python objects to JSON format.
Step 2: Use json.dumps()
json.dumps() takes a Python list and returns a string that represents the list in JSON format.
Step 3: Result is a JSON string
The output is a string that looks like a list but is formatted as JSON, which can be saved or sent over networks.
Alternative Approaches
import json my_list = [1, 2, 3] with open('data.json', 'w') as f: json.dump(my_list, f)
my_list = [1, 2, 3] json_string = str(my_list) print(json_string)
Complexity: O(n) time, O(n) space
Time Complexity
The time to convert grows linearly with the number of elements in the list because each element must be processed.
Space Complexity
The output string size grows linearly with the list size, so space used is proportional to the input list.
Which Approach is Fastest?
json.dumps() is optimized for conversion and faster than manual string building or using str().
| Approach | Time | Space | Best For |
|---|---|---|---|
| json.dumps() | O(n) | O(n) | Converting list to valid JSON string |
| json.dump() to file | O(n) | O(1) or O(n) depending on file buffering | Saving JSON directly to file |
| str() conversion | O(n) | O(n) | Quick string but not valid JSON |
json.dumps() to get a valid JSON string from a Python list.str() instead of json.dumps() creates a string that is not valid JSON.