How To Convert Python Dictionary To JSON?

Published on Aug. 22, 2023, 12:15 p.m.

To convert a Python dictionary to JSON, you can use the built-in json module in Python. The json.dumps() function can convert a Python dictionary to a JSON string. Here’s an example:

import json

my_dict = {'name': 'John', 'age': 30, 'city':'New York'}
json_string = json.dumps(my_dict)

print(json_string)

This will output:

{"name": "John", "age": 30, "city": "New York"}

In this example, we first import the json module, and then create a dictionary my_dict with some key-value pairs. Then, we use the json.dumps() function to convert the dictionary to a JSON string. Finally, we print the JSON string.

Note that json.dumps() returns a string, not a file. If you want to write the JSON to a file, you can open the file in “write” mode and use the json.dump() function instead:

import json

my_dict = {'name': 'John', 'age': 30, 'city':'New York'}
with open('my_file.json', 'w') as f:
    json.dump(my_dict, f)

In this example, we open the file my_file.json in “write” mode using the with statement. Then, we use the json.dump() function to write the dictionary to the file in JSON format. The resulting file will contain the JSON data.

Tags: