Converting a dictionary to JSON format allows you to serialize the dictionary into a JSON string, which can be used for data storage, transmission, or interoperability. In this blog post, we will explore different methods to convert a dictionary to JSON format in Python.
Method 1: Using the json module
# Method 1: Using the json module import json my_dict = {"name": "John", "age": 30, "city": "New York"} json_str = json.dumps(my_dict) print("JSON string:", json_str)
Output:
JSON string: {“name”: “John”, “age”: 30, “city”: “New York”}
Method 2: Using the str() function
# Method 2: Using the str() function my_dict = {"name": "John", "age": 30, "city": "New York"} json_str = str(my_dict) print("JSON string:", json_str)
Output:
JSON string: {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}