How to Convert Dict to JSON in Python

To convert a dictionary to JSON in Python, you can use the built-in json module. Simply call json.dumps() function with the dictionary as the parameter.

import json

# Create a Python dictionary
my_dict = {
"name": "John",
"age": 30,
"city": "New York"
}

# Convert the dictionary to JSON
json_data = json.dumps(my_dict)

# Print the JSON string
print(json_data)

Output:

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

In this example:

  1. We import the json module.
  2. We create a Python dictionary called my_dict with some key-value pairs.
  3. We use the json.dumps() function to convert the dictionary to a JSON string. The dumps() function serializes the dictionary into a JSON-formatted string.
  4. We print the resulting JSON string.

The json.dumps() function takes the dictionary as input and returns the corresponding JSON representation as a string.

You can also customize the JSON output by using additional parameters of json.dumps(). For example:

  • indent: Specifies the indentation level for pretty-printing the JSON string.
  • sort_keys: If set to True, the keys in the JSON output will be sorted alphabetically.
  • separators: Allows you to specify custom separators for the JSON string.

Here’s an example with some additional parameters:

json_data = json.dumps(my_dict, indent=4, sort_keys=True)
print(json_data)

Output:

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

In this case, the JSON string is pretty printed with an indentation level of 4 spaces, and the keys are sorted alphabetically.

Converting a dictionary to JSON is useful when you need to transmit data between different systems or when you want to store structured data in a portable format.

Stephen Mclin
Stephen Mclin

Hey, I'm Steve; I write about Python and Django as if I'm teaching myself. CodingGear is sort of like my learning notes, but for all of us. Hope you'll love the content!

Articles: 125

Leave a Reply

Your email address will not be published. Required fields are marked *