json.dump() in Python (original) (raw)

Last Updated : 13 Jan, 2026

The json.dump() function in Python is used to convert (serialize) a Python object into JSON format and write it directly to a file.

**Example: This example shows how to write a Python dictionary into a JSON file using json.dump().

Python `

import json data = {"name": "Joe", "age": 25} with open("data.json", "w") as f: json.dump(data, f)

`

**Output

Output1

Output

**Explanation:

Syntax

json.dump(obj, file, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None)

**Parameters:

Examples

**Example 1: This example writes dictionary data into a JSON file with indentation to make it easy to read.

Python `

import json d = {"id": 1, "name": "Lisa", "salary": 50000} with open("emp.json", "w") as f: json.dump(d, f, indent=4)

`

**Output

Output2

Output

**Explanation:

**Example 2: This example shows how skipkeys=True avoids errors when keys are not JSON-compatible.

Python `

import json d = {("x", "y"): 10, "z": 20} with open("data.json", "w") as f: json.dump(d, f, skipkeys=True)

`

**Output

Output2

output

**Explanation:

**Example 3: This example preserves non-ASCII characters in the JSON file.

Python `

import json d = {"msg": "¡Hola Mundo!"} with open("text.json", "w", encoding="utf-8") as f: json.dump(d, f, ensure_ascii=False)

`

**Output

Output3

Output

**Explanation:

dump() vs dumps()

Both json.dump() and json.dumps() are used to convert Python objects into JSON, but they differ in where the JSON output goes a file or a string.

dump() dumps()
Used when Python objects need to be written directly to a JSON file Used when Python objects need to be converted into a JSON-formatted string
Requires a file object as an argument Does not require a file, returns a string
Writes JSON directly to disk Stores JSON in memory as a string
Commonly used for saving data to files Commonly used for printing, logging, or API responses
Generally faster for file writing Slightly slower due to string creation