Skip to Content

Convert Python Dictionary to JSON

In this tutorial, we will look at how to convert a Python dictionary to a JSON in Python with the help of some examples.

How to convert a dictionary to JSON in Python?

You can use the Python built-in json library’s dumps() function to get a JSON string from a dictionary. The following is the syntax –

import json

# dictionary to json
my_json = json.dumps(my_dict)

It returns a JSON string which you can convert back to a dictionary using the json library’s loads() functions.

There are additional parameters as well to the json.dumps() function that you can use to modify the resulting JSON string. Some commonly used parameters are –

  1. sort_keys – This parameter is False by default. Pass True to sort the JSON string by the dictionary keys.
  2. indent – It’s None by default. Pass a non-negative integer or a string (for example “\t”) to specify the indent level in the JSON string

For more on the parameters of the json.dumps() function refer to its documentation.

Let’s look at some examples of using the above function.

1. Dictionary to JSON

We have a dictionary containing the names to department mappings of employees in an office. Let’s convert this dictionary to a JSON string using the json.dumps() function.

import json

# create a dictionary
employees = {
    "Jim": "Sales",
    "Dwight": "Sales",
    "Angela": "Accounting"
}
# convert dictionary to JSON
employees_json = json.dumps(employees)
# display the JSON and its type
print(employees_json)
print(type(employees_json))

Output:

{"Jim": "Sales", "Dwight": "Sales", "Angela": "Accounting"}
<class 'str'>

You can see that the resulting object is of the type str.

You can convert a JSON string back to a Python dictionary using the json.loads() functions.

# JSON string to dict
new_dict = json.loads(employees_json)
# display the dict and its type
print(new_dict)
print(type(new_dict))

Output:

{'Jim': 'Sales', 'Dwight': 'Sales', 'Angela': 'Accounting'}
<class 'dict'>

We get our original dictionary back.

2. Dictionary to JSON with sorted keys

Let’s now convert the same dictionary above to a JSON string but this time with sorted keys. For this, pass True to the sort_keys() parameter of the json.dumps() function.

import json

# create a dictionary
employees = {
    "Jim": "Sales",
    "Dwight": "Sales",
    "Angela": "Accounting"
}
# convert dictionary to JSON with sorted keys
employees_json = json.dumps(employees, sort_keys=True)
print(employees_json)

Output:

{"Angela": "Accounting", "Dwight": "Sales", "Jim": "Sales"}

You can see that the resulting JSON string is sorted on the dictionary keys.

3. Nested dictionary to JSON

The json.dumps() function works on nested dictionaries as well. This time let’s also specify 4 spaces as our indent level using the indent parameter.

import json

# create a dictionary
employees = {
    "Jim": {
        "Department": "Sales",
        "Salary": 60000
    },
    "Dwight": {
        "Department": "Sales",
        "Salary": 70000
    },
    "Angela": {
        "Department": "Accounting",
        "Salary": 65000
    }
}
# convert dictionary to JSON with custom indent
employees_json = json.dumps(employees, indent=4)
print(employees_json)

Output:

{
    "Jim": {
        "Department": "Sales",
        "Salary": 60000
    },
    "Dwight": {
        "Department": "Sales",
        "Salary": 70000
    },
    "Angela": {
        "Department": "Accounting",
        "Salary": 65000
    }
}

Here we convert a nested dictionary to a JSON string with a custom indent of 4 spaces. You can see that for each employee we have a dictionary containing information specific to that employee.

You might also be interested in –

  1. Write a Pandas DataFrame to a JSON File
  2. Python – Convert Dictionary String to Dictionary


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush

    Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.