json.dumps() is a function in Python’s json module that converts a Python object into a JSON formatted string. It allows you to serialize Python objects such as dictionaries, lists, and more into JSON format.
For Example:
Python
import json
# Creating a dictionary
d = {1: 'Welcome', 2: 'to', 3: 'Geeks', 4: 'for', 5: 'Geeks'}
# Convert the dictionary to a JSON string
json_s = json.dumps(d)
print(json_s)
print(type(json_s))
OutputEquivalent JSON string of dictionary: {"1": "Welcome", "2": "to", "3": "Geeks", "4": "for", "5": "Geeks"}
<class 'str'>
In the above example, the json.dumps() method converts a dictionary object into a JSON-formatted string.
Syntax
json.dumps(obj, skipkeys=False, ensure_ascii=True,
allow_nan=True, indent=None, separators=None,
sort_keys=False)
Parameters:
- obj: Python object to convert (dict, list, string, etc.)
- skipkeys: Skip non-serializable keys instead of raising an error
- ensure_ascii: If True (default), escapes non-ASCII chars; set False to keep them
- allow_nan: Allows special float values (NaN, Infinity)
- indent: Add spaces for pretty-printing
- separators: Change default separators (items, and key/value :)
- sort_keys: Sorts dictionary keys alphabetically
Return Type: string object (str).
Examples of json.dumps
Example 1: Using skipkeys to Skip Non-Serializable Keys
This example shows how the skipkeys parameter allows skipping non-serializable keys like tuples.
Python
import json
# Dictionary with a tuple as key
Dictionary = {('address', 'street'): 'Brigade Road', 2: 'to', 3: 'Geeks', 4: 'for', 5: 'Geeks'}
# Convert to JSON string, skipping non-serializable keys
json_string = json.dumps(Dictionary, skipkeys=True)
print('Equivalent JSON string of dictionary:', json_string)
OutputEquivalent JSON string of dictionary: {"2": "to", "3": "Geeks", "4": "for", "5": "Geeks"}
Explanation:
- A dictionary is created with a tuple key (not supported in JSON).
- json.dumps(..., skipkeys=True) converts it into a JSON string while skipping invalid keys.
- The tuple key–value pair is ignored, and only valid entries appear in the output.
- This shows how skipkeys=True safely handles non-serializable keys.
Example 2: Handling NaN and Infinity with allow_nan
In this example, we demonstrate the handling of NaN and Infinity by using the allow_nan parameter.
Python
import json
# Dictionary with NaN value
Dictionary = {1: 'Welcome', 2: 'to', 3: 'Geeks', 4: 'for', 5: 'Geeks', 6: float('nan')}
# Convert to JSON string, allowing NaN values
json_string = json.dumps(Dictionary, skipkeys=True, allow_nan=True)
print('Equivalent JSON string of dictionary:', json_string)
OutputEquivalent JSON string of dictionary: {"1": "Welcome", "2": "to", "3": "Geeks", "4": "for", "5": "Geeks", "6": NaN}
Explanation:
- A dictionary is created with a NaN (Not a Number) value using float('nan').
- json.dumps(..., allow_nan=True) allows converting special float values (NaN, Infinity) into JSON.
- The NaN value is kept in the output instead of causing an error.
Example 3: Pretty Printing with indent
By default, JSON is printed in one line. The indent parameter makes it easier to read by adding spaces. In this example, we use the indent parameter to format the JSON output with indentation.
Python
import json
# Dictionary to be converted
Dictionary = {1: 'Welcome', 2: 'to', 3: 'Geeks', 4: 'for', 5: 'Geeks', 6: float('nan')}
# Convert to JSON with indentation for pretty-printing
json_string = json.dumps(Dictionary, skipkeys=True, allow_nan=True, indent=6)
print('Equivalent JSON string of dictionary:', json_string)
OutputEquivalent JSON string of dictionary: {
"1": "Welcome",
"2": "to",
"3": "Geeks",
"4": "for",
"5": "Geeks",
"6": NaN
}
Explanation:
- A dictionary is created with keys and values (including a NaN value).
- json.dumps(..., indent=6): converts the dictionary into a JSON string with 6 spaces indentation for pretty-printing.
- The output is neatly formatted, making it easier to read compared to a single-line JSON string.
Example 4: Customizing Separators for JSON
JSON uses "," and ":" by default as seperators for key-value pairs but we can customize it using the seperators parameters
Python
import json
# Dictionary to be converted
Dictionary = {1: 'Welcome', 2: 'to', 3: 'Geeks', 4: 'for', 5: 'Geeks', 6: float('nan')}
# Customize separators
json_string = json.dumps(Dictionary, skipkeys=True, allow_nan=True, indent=6, separators=(". ", " = "))
print('Equivalent JSON string of dictionary:', json_string)
OutputEquivalent JSON string of dictionary: {
"1" = "Welcome".
"2" = "to".
"3" = "Geeks".
"4" = "for".
"5" = "Geeks".
"6" = NaN
}
Explanation:
- A dictionary is created with string values and a NaN.
- json.dumps(..., separators=(". ", " = ")) customizes how items and keys are separated.
- ". ": separates items.
- " = ": separates keys from values.
- The result is a JSON string with a custom format instead of the default , and :.
Example 5: Sorting Dictionary Keys with sort_keys
By default, JSON preserves dictionary order. With sort_keys=True, keys are sorted alphabetically.
Python
import json
# Dictionary to be converted
Dictionary = {'c': 'Welcome', 'b': 'to', 'a': 'Geeks'}
# Convert to JSON string, sorting keys
json_string = json.dumps(Dictionary, indent=6, separators=(". ", " = "), sort_keys=True)
print('Equivalent JSON string of dictionary:', json_string)
OutputEquivalent JSON string of dictionary: {
"a" = "Geeks".
"b" = "to".
"c" = "Welcome"
}
Explanation:
- A dictionary is created with string keys.
- json.dumps(..., indent=6, separators=(". ", " = "), sort_keys=True) converts it into a JSON string.
- Keys are sorted alphabetically, items are separated by . , and indentation makes it easy to read.
- The final result is a neatly formatted JSON string.
Related Articles:
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice