How to convert a Python dictionary to JSON?

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

In Python, you can use the json module to convert a Python dictionary to a JSON object. The json module provides two methods to do this: json.dumps() and json.dump().

Here’s an example using json.dumps():

import json

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

print(json_object)

This will output a string representation of the JSON object:

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

Alternatively, you can use json.dump() to write the JSON directly to a file:

import json

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

with open('output.json', 'w') as f:
    json.dump(my_dict, f)

This will write the JSON object to a file called output.json.

Note that the dictionary keys must be strings to be serialized in JSON format, and that the JSON format only supports a limited set of data types, including strings, numbers, booleans, lists, and dictionaries. If your dictionary contains custom objects or other data types, you will need to write custom serialization code to convert them to JSON.