To convert a dictionary to a JSON string in Python, you can use the `json.dumps()` function from the `json` module. This allows you to create a JSON string representation of the dictionary.
We can convert a dictionary to a JSON string in Python using the `json.dumps()` function. This example demonstrates how to declare and initialize a dictionary, use the `json.dumps()` function to convert the dictionary to a JSON string, and print the resulting JSON string.
For example,
my_dict
with integer keys and string values.import json
my_dict = {
1: 'One',
2: 'Two',
3: 'Three'
}
# Convert the dictionary to a JSON string using json.dumps()
json_string = json.dumps(my_dict)
# Print the resulting JSON string
print('JSON string:')
print(json_string)
JSON string: {"1": "One", "2": "Two", "3": "Three"}
We can convert a dictionary with complex values to a JSON string in Python using the `json.dumps()` function. This example demonstrates how to declare and initialize a dictionary with complex values, use the `json.dumps()` function to convert the dictionary to a JSON string, and print the resulting JSON string.
For example,
my_dict
with integer keys and values that are dictionaries.import json
my_dict = {
1: {'name': 'John', 'age': 30},
2: {'name': 'Jane', 'age': 25}
}
# Convert the dictionary to a JSON string using json.dumps()
json_string = json.dumps(my_dict, indent=4)
# Print the resulting JSON string
print('JSON string:')
print(json_string)
JSON string: { "1": { "name": "John", "age": 30 }, "2": { "name": "Jane", "age": 25 } }
In this tutorial, we learned How to Convert a Dictionary to a JSON String in Python language with well detailed examples.