How to convert a dictionary to JSON in Python?

Dictionaries are one of the most widely used data structures in Python, while JSON is a highly recognized format for data. To make data represented by a dictionary usable in the JSON format, we would first need to convert it to JSON

Before the code demonstration, let's first concisely cover both of these individually.

JSON format

JSON, also known as JavaScript Object Notation, is an efficient and lightweight interchange format to efficiently depict data that is both easy to read or write for us and for machines to parse and generate.

JSON representation
JSON representation

JSON rules to remember

  1. This format consists of key-value pairs which are then enclosed in curly braces.

  2. The key and the value are separated using a colon.

  3. The keys are always a string.

  4. The value could be of various types, for instance, booleans, arrays, strings, objects, null, etc.

  5. Keys can be repeated since they are ordered, but it is not recommended.

  6. The keys and values must be enclosed in double quotes.

{
"blackHole": {
"name": "Cygnus X-1",
"type": "Stellar",
"mass": 15,
"isSupermassive": false,
"isRotating": true,
"spin": 0.98,
"discoveredBy": null,
"aliases": ["HDE 226868"],
"details": {
"discoveryDate": "1964",
"distance": 6100.0,
"galacticCoordinates": {
"l": 71.335,
"b": -3.063
}
}
}
}
A JSON blackhole object with various key-value pairs

Dictionaries in Python

A dictionary is a built-in data structure that Python provides us with. It allows us to hold key-value pairs as a collection and is similar to maps or hash tables. We can say that it's a mutable, unordered, and indexed collection of elements. It's also similar to JSON due to these key-value pairs.

JSON representation
JSON representation

Dictionary rules in Python

  1. The format includes the dictionary's name followed by an == sign which is finally followed by the dictionary content in curly braces.

  2. The keys must be unique and immutable.

  3. Single quotes can be used for keys and values.

  4. Dictionaries can grow or shrink since elements can be added, removed, or modified.

  5. Values can be of any type, including mutable objects like lists or even dictionaries.

  6. The keys could be any hashable object and aren't limited to strings.

blackHole = {
'name': 'Cygnus X-1',
'type': 'Stellar',
'mass': 15,
'isSupermassive': False,
'isRotating': True,
'spin': 0.98,
'discoveredBy': None,
'aliases': ['HDE 226868'],
42: 'Meaning of Life',
('x', 'y'): 'Coordinates',
True: 'Boolean Key'
}
A dictionary in Python with various key-value pairs

We're now equipped with the necessary knowledge and can convert a dictionary to JSON.

Key-value pairs
Key-value pairs

Converting a dictionary to JSON

json.dumps method

The json module in Python offers functionalities related to encoding and decoding data in JSON. Since our goal is to convert a dictionary to this format, we can make use of the dumps function put forth by this module.

Syntax

jsonData = json.dumps(dictName)
Replace dictName with the dictionary's name which is to be converted

Parameters

The only necessary argument to be passed to this function is the dictionary input itself. Apart from that, there are a few optional parameters we can add for customizations.

  1. indent: Specifies the number of spaces for indentation in the JSON string.

  2. sort_keys: Controls whether keys in the JSON string are sorted alphabetically.

  3. separators: Customizes the separators used in the JSON string.

  4. ensure_ascii: Determines whether non-ASCII characters are escaped in the JSON string.

Note: Escaping means representing non-ASCII characters using a Unicode escape sequence.

The result

The variable to which the json.dump method assigns the result now contains a JSON formatted string.

Let's see this in action now!

Code sample

import json

star = {

    'name': 'Sirius',
    "spectral_type": 'A1V',
    'temperature': '9640K',
    'distance_ly': 8.6,
    'discovery_year': 1844,
    'aliases': ['Dog Star'],
    'details': {
        'constellation': 'Canis Major',
        'right_ascension': '06h 45m 08.9173s',
        'declination': '-16 42 58.017',
        'main_sequence': True
    }

}

JSONData = json.dumps(
    star,
    indent = 4,
    sort_keys = True,
    separators = (",", ": "),
    ensure_ascii = False
)
print(JSONData)

Code explanation

  • Line 1: We import the json module in Python.

  • Lines 3–18: We define a dictionary named star with the keys name, spectral_type, temperature, distance_ly, aliases, and details.

  • Line 20: A variable JSONData is created so that it can be assigned the JSON object after conversion. We call the json.dumps method to achieve this conversion.

  • Line 21: We pass the star dictionary to this method.

  • Line 22: We pass indent = 4 to json.dumps to specify that the resulting JSON string should be indented with 4 spaces for better readability.

  • Line 23: We pass sort_keys = True to json.dumps to ensure that the keys in the resulting JSON string are sorted in alphabetical order.

  • Line 24: We pass separators = (",", ": ") to json.dumps to specify that a comma and space should be used as the element separator while a colon and space should be used as the key-value separator.

  • Line 25: Lastly, we pass ensure_ascii = False to json.dumps to ensure that non-ASCII characters in the input data are preserved without escaping.

  • Line 26: Our dictionary is now finally converted and stored in JSONData! We can finally print it to see the result using print(JSONData).

Output

Congratulations, our code is now ready to run! The following image depicts the output of the star dictionary we converted to JSON.

JSON result
JSON result

You can also experiment with the executable code above to convert your own dictionary when you click on "Run".

Test yourself now!

How well do you understand the json.dumps method?

Question

Consider the following dictionary: data = {"b": 2, "a": 1, "c": 3}. If we use the json.dumps method with sort_keys = True to convert this to a JSON string, what will be the output?

Show Answer

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved