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.
Syntax
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
Parameters:
- obj: The Python object (e.g., dictionary, list) that needs to be converted into a JSON formatted string.
- skipkeys: If set to True, non-serializable keys (like tuples) will be skipped, otherwise, a TypeError will be raised.
- ensure_ascii: If True, non-ASCII characters are escaped. If False, they are output as-is.
- check_circular: If False, circular references (e.g., an object referencing itself) are ignored, otherwise a ValueError is raised.
- allow_nan: If set to True, Python's special float values (NaN, Infinity) are converted into JavaScript’s equivalents (NaN, Infinity).
- indent: Defines the indentation level for pretty-printing. Pass an integer value to set spaces per level. None gives the most compact output.
- separators: Defines how the JSON objects will be separated (item separator and key separator).
- default: A function that will be used to serialize non-serializable objects.
- sort_keys: If True, the output will have dictionaries sorted by key.
Let's look at some examples:
Example 1: Converting Python Dictionary to JSON String
In this example, we will convert a simple Python dictionary into a JSON formatted string using json.dumps().
Python
import json
# Creating a dictionary
Dictionary = {1: 'Welcome', 2: 'to', 3: 'Geeks', 4: 'for', 5: 'Geeks'}
# Convert the dictionary to a JSON string
json_string = json.dumps(Dictionary)
print('Equivalent JSON string of dictionary:', json_string)
print(type(json_string))
Output
Equivalent json string of dictionary: {"1": "Welcome", "2": "to", "3": "Geeks", "4": "for", "5": "Geeks"}
<class 'str'>
Example 2: 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)
Output:
Equivalent json string of dictionary: {"2": "to", "3": "Geeks", "4": "for", "5": "Geeks"}
Example 3: Handling NaN and Infinity with allow_nan
Here, 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)
Output:
Equivalent json string of dictionary: {"2": "to", "3": "Geeks", "4": "for", "5": "Geeks", "6": NaN}
Example 4: Pretty-Printing JSON with Indentation
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)
Output:
Equivalent json string of dictionary: {
"2": "to",
"3": "Geeks",
"4": "for",
"5": "Geeks",
"6": NaN
}
Example 5: Customizing Separators for JSON
Here, we use the separators parameter to customize the separators between items and keys.
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)
Output:
Equivalent json string of dictionary: {
"2" = "to".
"3" = "Geeks".
"4" = "for".
"5" = "Geeks".
"6" = NaN
}
Example 6: Sorting Dictionary Keys with sort_keys
This example shows how to sort dictionary keys alphabetically using the sort_keys parameter.
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)
Output:
Equivalent json string of dictionary: {
"a" = "Geeks".
"b" = "to".
"c" = "Welcome"
}
Note: For more information, refer to Read, Write and Parse JSON using Python