Python How to Convert Dictionary to JSON String
json.dumps() function from Python's json module to convert a dictionary to a JSON string, like json.dumps(your_dict).Examples
How to Think About It
json module has a function called dumps() that does this conversion easily by taking the dictionary and returning a string with JSON formatting.Algorithm
Code
import json my_dict = {"name": "Alice", "age": 30} json_string = json.dumps(my_dict) print(json_string)
Dry Run
Let's trace converting {'name': 'Alice', 'age': 30} to JSON string.
Import json module
json module is ready to use.
Create dictionary
my_dict = {'name': 'Alice', 'age': 30}
Convert dictionary to JSON string
json_string = json.dumps(my_dict) results in '{"name": "Alice", "age": 30}'
| Step | Dictionary | JSON String |
|---|---|---|
| Initial | {'name': 'Alice', 'age': 30} | N/A |
| After dumps() | {'name': 'Alice', 'age': 30} | {"name": "Alice", "age": 30} |
Why This Works
Step 1: Import json module
The json module provides tools to work with JSON data in Python.
Step 2: Use json.dumps()
json.dumps() takes a Python dictionary and converts it into a JSON formatted string.
Step 3: Print or use the JSON string
The result is a string that can be saved, sent, or used where JSON format is needed.
Alternative Approaches
import json my_dict = {"name": "Alice", "age": 30} json_string = json.dumps(my_dict, indent=4) print(json_string)
import json my_dict = {"b": 2, "a": 1} json_string = json.dumps(my_dict, sort_keys=True) print(json_string)
Complexity: O(n) time, O(n) space
Time Complexity
The time depends on the number of items in the dictionary because json.dumps() processes each key-value pair once.
Space Complexity
The space used is proportional to the size of the dictionary since the output is a string representation of all items.
Which Approach is Fastest?
Using json.dumps() directly is the fastest and simplest way; adding options like indent or sort_keys adds minor overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| json.dumps() | O(n) | O(n) | Simple conversion |
| json.dumps() with indent | O(n) | O(n) | Readable JSON output |
| json.dumps() with sort_keys | O(n log n) | O(n) | Sorted keys in JSON |