![]() |
VOOZH | about |
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.
{"a": "Hello", "b": "World"}
<class 'str'>
Explanation:
json.dumps(obj, skipkeys=False, ensure_ascii=True, allow_nan=True, indent=None, separators=None, sort_keys=False)
Parameters:
Return Type: string object (str).
Example 1: This example demonstrates how skipkeys=True ignores dictionary keys that are not JSON-compatible.
{"a": 1}
Explanation:
Example 2: This example formats JSON output to make it more readable using indentation.
{
"a": 1,
"b": 2,
"c": 3
}
Explanation:
Example 3: This example sorts dictionary keys alphabetically before converting them to JSON.
{"a": 1, "b": 2, "c": 3}
Explanation:
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.
[10, 20, 30, 40]
Explanation: