Python Program to Convert Dictionary to JSON
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.dumps() function which takes the dictionary and returns a JSON formatted string. This string can then be saved or sent anywhere JSON is needed.Algorithm
Code
import json my_dict = {"name": "Alice", "age": 30} json_str = json.dumps(my_dict) print(json_str)
Dry Run
Let's trace converting {'name': 'Alice', 'age': 30} to JSON string.
Import json module
The program loads the json module to access JSON functions.
Create dictionary
my_dict = {'name': 'Alice', 'age': 30}
Convert dict to JSON string
json_str = json.dumps(my_dict) results in '{"name": "Alice", "age": 30}'
Print JSON string
Output is printed: {"name": "Alice", "age": 30}
| Step | Action | Value |
|---|---|---|
| 1 | Import json module | json module ready |
| 2 | Create dictionary | {'name': 'Alice', 'age': 30} |
| 3 | Convert dict to JSON string | {"name": "Alice", "age": 30} |
| 4 | Print JSON string | Printed output |
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() converts a Python dictionary into a JSON formatted string.
Step 3: Print the JSON string
Printing shows the JSON string which can be used for data exchange or storage.
Alternative Approaches
import json my_dict = {"name": "Alice", "age": 30} with open('data.json', 'w') as f: json.dump(my_dict, f) print('JSON saved to file')
import json my_dict = {"name": "Alice", "age": 30} json_str = json.dumps(my_dict, indent=4) print(json_str)
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 grows with the size of the dictionary since the JSON string stores all data.
Which Approach is Fastest?
Using json.dumps() is fast and simple for in-memory conversion; writing directly to a file with json.dump() avoids storing the whole string in memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| json.dumps() | O(n) | O(n) | Converting dict to JSON string in memory |
| json.dump() to file | O(n) | O(1) | Saving JSON directly to a file without extra memory |
| json.dumps() with indent | O(n) | O(n) | Readable JSON output for humans |