Python Write JSON to File: json.dump() with Examples

Write JSON to a file in Python with json.dump(). Learn indent, sort_keys, ensure_ascii for non-ASCII text, the conversion rules and default for dates.

json editor

To write JSON to a file in Python, we open the file in write mode and pass the Python object and the file to json.dump(), which converts the object to JSON text and writes it. The indent and sort_keys arguments control the formatting, and ensure_ascii=False keeps non-English text readable.

import json

py_dict = {"id": 1}

with open("users.json", "w", encoding="utf-8") as json_file:
    json.dump(py_dict, json_file, indent=4, sort_keys=True)

We go through the parameters of json.dump(), the conversion rules, pretty printing, non-ASCII text, and the TypeError for objects that JSON cannot represent. The examples run on Python 3.14.

1. json.dump() Method

The json.dump() function serializes a Python object as a JSON formatted stream into a given file. Its sibling json.dumps() returns the same JSON as a string instead of writing it.

1.1. Syntax, Parameters and Return Value

The signature lists every keyword argument with its default value.

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
          allow_nan=True, cls=None, indent=None, separators=None,
          default=None, sort_keys=False, **kw) -> None

Except obj and fp, all parameters are optional keyword arguments, and the function returns None. These are the ones we use most often.

  • obj is the Python object to write, and fp is a file opened in text write mode.
  • indent pretty-prints the output with the given number of spaces.
  • sort_keys writes dictionary keys in sorted order when it is True.
  • ensure_ascii escapes non-ASCII characters as \uXXXX when it is True, the default.
  • separators sets the item and key separators, for example (“,”, “:”) for compact output.
  • default is a function called for objects JSON cannot represent; without it, they raise TypeError.
  • allow_nan controls whether NaN and Infinity are written; they are not valid JSON.

1.2. Conversion Rules

The json.dump() function uses these rules to convert Python objects to JSON. Dictionary keys of type str, int, float, bool or None become JSON strings, and other key types such as tuples raise TypeError.

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
True / Falsetrue / false
Nonenull

2. Python Write JSON to File Examples

The examples write the same small dictionary in different formats, so we can compare the output files.

Example 1: Writing Python Dict to File

Without formatting arguments, the whole object goes on one line, which is the smallest file.

py_dictionary = {"Name": "Lokesh", "Age": 39, "Blog": "howtodoinjava"}

with open("users.json", "w", encoding="utf-8") as json_file:
    json.dump(py_dictionary, json_file)
{"Name": "Lokesh", "Age": 39, "Blog": "howtodoinjava"}

Example 2: Write Pretty Printed JSON to File

For pretty printing, we pass the indent parameter, here with sorted keys.

with open("users.json", "w", encoding="utf-8") as json_file:
    json.dump(py_dictionary, json_file, indent=4, sort_keys=True)
{
    "Age": 39,
    "Blog": "howtodoinjava",
    "Name": "Lokesh"
}

Example 3: Write Non-ASCII Text

By default, json.dump() and json.dumps() escape every non-ASCII character, so we pass ensure_ascii=False to keep the text readable, and we open output files with encoding=”utf-8″. The comments show the printed strings.

city = {"City": "Málaga"}
escaped = json.dumps(city)                       # '{"City": "M\u00e1laga"}'
readable = json.dumps(city, ensure_ascii=False)  # '{"City": "Málaga"}'

Example 4: Handle Objects JSON Cannot Write

Sets, dates and custom classes raise TypeError. The default parameter converts them, and default=str is enough for dates.

from datetime import date

event = {"name": "Launch", "on": date(2026, 11, 2)}
bad = json.dumps(event)                   # TypeError: Object of type date is not JSON serializable
good = json.dumps(event, default=str)     # '{"name": "Launch", "on": "2026-11-02"}'

For classes with several fields, see custom class serialization. To add records to an existing file instead of replacing it, see appending to a JSON file.

3. Writing a List of Records and Reading It Back

A common case is writing a list of dictionaries, for example rows from a database, and reading them back later. A round trip in a test catches values that do not survive the conversion, such as tuples turning into lists.

orders = [{"id": 1, "items": ("tea", "milk")}, {"id": 2, "items": ("rice",)}]

with open("orders.json", "w", encoding="utf-8") as f:
    json.dump(orders, f, indent=2)

with open("orders.json", encoding="utf-8") as f:
    loaded = json.load(f)

items = loaded[0]["items"]      # ['tea', 'milk'], a list after loading
equal = loaded == orders        # False, tuples became lists

For an API response or a message queue, compact output saves bytes, and separators=(“,”, “:”) removes the spaces that json.dumps() adds by default.

compact = json.dumps({"id": 1, "ok": True}, separators=(",", ":"))   # '{"id":1,"ok":true}'

4. dump(), dumps() and Escaped Characters

These questions come from the first JSON files a developer opens and inspects.

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

The json.dump() function writes to a file object and returns None, while json.dumps() returns the JSON as a string. The “s” stands for string.

4.2. How do we write NaN or Infinity?

By default, json.dump() writes them as NaN and Infinity, which are not valid JSON and break other parsers. Passing allow_nan=False raises ValueError instead, so we replace such values with None before writing.

4.3. How do we pretty-print an existing JSON file?

The command python -m json input.json prints it with indentation (Python 3.14), and python -m json.tool input.json works on older versions.

5. Conclusion

Writing JSON takes open() in write mode with encoding=”utf-8″ and one call to json.dump(). We add indent for files people read, ensure_ascii=False for non-English text, and a default function for dates and custom objects.

6. References

Happy Learning !!

Source Code on Github

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.