The json.dumps() function in Python converts a Python object (such as a dictionary or list) into a JSON-formatted string. It is mainly used when you need to send data over APIs, store structured data or serialize Python objects into JSON text.
Example: This example shows how to convert a Python dictionary into a JSON string.
import json
d = {"a": "Hello", "b": "World"}
s = json.dumps(d)
print(s)
print(type(s))
Output
{"a": "Hello", "b": "World"}
<class 'str'>
Explanation:
- json.dumps(d) converts the dictionary d into a JSON string.
- The output type is str, not a dictionary.
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: Ignores unsupported keys instead of raising an error
- ensure_ascii: Escapes non-ASCII characters if True
- allow_nan: Allows NaN, Infinity values
- indent: Formats JSON with indentation
- separators: Custom separators for items and key–value pairs
- sort_keys: Sorts dictionary keys alphabetically
Return Type: string object (str).
Examples
Example 1: This example demonstrates how skipkeys=True ignores dictionary keys that are not JSON-compatible.
import json
d = {("x", "y"): 10, "a": 1}
s = json.dumps(d, skipkeys=True)
print(s)
Output
{"a": 1}
Explanation:
- JSON does not support tuple keys.
- skipkeys=True removes invalid keys automatically.
Example 2: This example formats JSON output to make it more readable using indentation.
import json
d = {"a": 1, "b": 2, "c": 3}
s = json.dumps(d, indent=4)
print(s)
Output
{
"a": 1,
"b": 2,
"c": 3
}
Explanation:
- indent=4 adds spacing and line breaks.
- The JSON string becomes easy to read.
Example 3: This example sorts dictionary keys alphabetically before converting them to JSON.
import json
d = {"c": 3, "a": 1, "b": 2}
s = json.dumps(d, sort_keys=True)
print(s)
Output
{"a": 1, "b": 2, "c": 3}
Explanation:
- sort_keys=True sorts keys alphabetically.
- Useful for consistent JSON output.
Example 4: This example shows how json.dumps() converts a Python list into a JSON-formatted string, which is commonly used when sending list data through APIs.
import json
lst = [10, 20, 30, 40]
s = json.dumps(lst)
print(s)
Output
[10, 20, 30, 40]
Explanation:
- json.dumps(lst) converts the Python list lst into a JSON array.
- The result is a JSON string representation of the list.