json.dump() Function Explained

json.dump() writes Python data to a file in JSON format.

Use it when you want to save data like dictionaries or lists into a .json file. This is a common way to store settings, API data, or simple structured data.

Quick example #

import json

data = {"name": "Alice", "age": 30}

with open("data.json", "w") as file:
    json.dump(data, file)

Use json.dump() when you want to write Python data directly to a file as JSON.

What json.dump() does #

json.dump():

  • Writes Python data to a file in JSON format
  • Takes a Python object and a file object
  • Is commonly used with dictionaries and lists
  • Does not return the JSON string

This part is important:

  • json.dump() writes to a file
  • It does not give you the JSON text back as a return value

If you need the JSON text as a string instead, see json.dumps() explained.

Basic syntax #

The basic syntax is:

json.dump(obj, file)
  • obj is the Python data you want to save
  • file must be an open file object in write mode
  • It is usually used inside a with open(...) block

Example:

import json

data = {"city": "Paris"}

with open("data.json", "w") as file:
    json.dump(data, file)

If you are not familiar with opening files, see open() explained and how to write to a file in Python.

Simple working example #

Here is a complete example that writes a dictionary to a JSON file:

import json

person = {
    "name": "Alice",
    "age": 30,
    "is_admin": False
}

with open("data.json", "w") as file:
    json.dump(person, file)

What this code does #

  • Opens data.json in write mode using "w"
  • Creates the file if it does not exist
  • Overwrites the file if it already exists
  • Writes the dictionary as JSON

Resulting file content #

After running the code, data.json will contain:

{"name": "Alice", "age": 30, "is_admin": false}

Notice that JSON uses:

  • false instead of Python False
  • null instead of Python None

If you want a broader introduction, see the Python JSON module overview.

Common useful options #

json.dump() has several optional arguments that are often useful.

Use indent to make JSON easier to read #

Without indent, JSON is usually written on one line.

import json

data = {"name": "Alice", "age": 30, "skills": ["Python", "SQL"]}

with open("data.json", "w") as file:
    json.dump(data, file, indent=2)

Result in the file:

{
  "name": "Alice",
  "age": 30,
  "skills": [
    "Python",
    "SQL"
  ]
}

This is often called pretty-printed JSON. For more, see how to pretty-print JSON in Python.

Use sort_keys=True to sort dictionary keys #

import json

data = {"b": 2, "a": 1, "c": 3}

with open("data.json", "w") as file:
    json.dump(data, file, indent=2, sort_keys=True)

This writes the keys in alphabetical order:

{
  "a": 1,
  "b": 2,
  "c": 3
}

Use ensure_ascii=False for non-English characters #

By default, some non-English characters are escaped.

import json

data = {"name": "José", "city": "München"}

with open("data.json", "w", encoding="utf-8") as file:
    json.dump(data, file, ensure_ascii=False, indent=2)

This keeps the characters readable in the file.

json.dump() vs json.dumps() #

These two functions are similar, but they do different jobs.

json.dump() #

  • Writes JSON directly to a file
import json

data = {"name": "Alice"}

with open("data.json", "w") as file:
    json.dump(data, file)

json.dumps() #

  • Returns JSON as a string
import json

data = {"name": "Alice"}

json_text = json.dumps(data)
print(json_text)

Output:

{"name": "Alice"}

Use:

  • json.dump() for saving JSON to files
  • json.dumps() when you need the JSON text in memory

You can also see how to convert a dictionary to JSON in Python.

What data types work #

json.dump() works with standard JSON-compatible Python types:

  • dict
  • list
  • str
  • int
  • float
  • bool
  • None

Nested combinations of these types also work.

Example:

import json

data = {
    "user": "Alice",
    "age": 30,
    "active": True,
    "scores": [10, 20, 30],
    "profile": {
        "country": "UK",
        "verified": False
    },
    "nickname": None
}

with open("data.json", "w") as file:
    json.dump(data, file, indent=2)

Types that do not work directly #

Some Python types are not JSON serializable by default, such as:

  • set
  • Custom class objects

This example causes an error:

import json

data = {"numbers": {1, 2, 3}}

with open("data.json", "w") as file:
    json.dump(data, file)

Typical error:

TypeError: Object of type set is not JSON serializable

To fix this, convert the set to a list first:

import json

data = {"numbers": list({1, 2, 3})}

with open("data.json", "w") as file:
    json.dump(data, file)

For this specific problem, see TypeError: Object is not JSON serializable.

Common errors and fixes #

Here are the most common problems beginners run into with json.dump().

1. Passing a file path instead of a file object #

This is wrong:

import json

data = {"name": "Alice"}
json.dump(data, "data.json")

json.dump() expects an open file object, not a file name string.

Correct version:

import json

data = {"name": "Alice"}

with open("data.json", "w") as file:
    json.dump(data, file)

2. Using unsupported data types #

This fails because set is not supported:

import json

data = {"items": {"apple", "banana"}}

with open("data.json", "w") as file:
    json.dump(data, file)

Fix it by converting the set:

import json

data = {"items": list({"apple", "banana"})}

with open("data.json", "w") as file:
    json.dump(data, file)

3. Confusing json.dump() with json.dumps() #

If you want to save to a file, use json.dump().

If you want a string, use json.dumps().

4. Opening the file in the wrong mode #

This is wrong:

import json

data = {"name": "Alice"}

with open("data.json", "r") as file:
    json.dump(data, file)

The file is opened in read mode, so Python cannot write to it.

Use write mode:

import json

data = {"name": "Alice"}

with open("data.json", "w") as file:
    json.dump(data, file)

5. Trying to save custom objects directly #

This usually fails:

import json

class User:
    def __init__(self, name):
        self.name = name

user = User("Alice")

with open("data.json", "w") as file:
    json.dump(user, file)

Fix it by converting the object to a dictionary:

import json

class User:
    def __init__(self, name):
        self.name = name

user = User("Alice")
data = {"name": user.name}

with open("data.json", "w") as file:
    json.dump(data, file)

Helpful debugging checks #

If json.dump() is failing, these checks can help:

print(type(data))
print(data)
print(json.dumps(data, indent=2))
print(file.mode)

These help you check:

  • What type your data is
  • What values it contains
  • Whether the data can be converted to JSON
  • Whether the file is open in the correct mode

FAQ #

What is the difference between json.dump() and json.dumps()? #

json.dump() writes JSON to a file. json.dumps() returns JSON as a string.

Does json.dump() create a file? #

It writes to a file object. If you open a new file in write mode, Python creates it.

Can json.dump() write a list? #

Yes. It can write lists, dictionaries, strings, numbers, booleans, and None.

Why does json.dump() give a TypeError? #

Usually because the data contains a type that JSON cannot serialize, such as a set or custom object.

See also #

Press Esc to close