json.dump() is a method in Python's json module used to serialize a Python object into JSON format and write it directly to a file. It is commonly used for saving data to disk in a structured, human-readable format.

Key Features:

  • Purpose: Writes JSON data to a file (e.g., data.json).

  • Syntax: json.dump(obj, file, indent=None, sort_keys=False, ensure_ascii=True, ...)

  • Parameters:

    • obj: The Python object (dict, list, etc.) to convert.

    • file: A file object opened in write mode ('w' or 'wb').

    • indent: Adds whitespace for readable (pretty-printed) output (e.g., indent=4).

    • sort_keys: If True, sorts dictionary keys alphabetically.

    • ensure_ascii: If False, allows non-ASCII characters (e.g., é, 中文) to be written as-is.

Example:

import json

data = {"name": "Alice", "age": 30, "city": "New York"}

with open("data.json", "w") as f:
    json.dump(data, f, indent=4)

Output (in data.json):

{
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

Difference from json.dumps():

  • json.dump()writes to a file.

  • json.dumps()returns a JSON string (useful for printing, logging, or sending over a network).

Use json.dump() when you need to save structured data persistently.

JSON data in python is essentially a dictionary (at least they are interchangeable, there are some minor differences with the formatting). Have you tried saving a dictionary to a simple text file? my_data = { 'a': [1, 2, 3], 'b': {'foo': 'bar', 'baz': [4, 5, 6]} } with open('test_file.txt', 'w') as file: file.write(my_data) This is not possible because Python expects a string that it can write to a file. It doesn't know how to turn a dictionary into something it can write to a file. But, maybe you then do this instead: my_data = { "a": [1, 2, 3], "b": {"foo": "bar", "baz": [4, 5, 6]} } with open('test_file.txt', 'w') as file: # cast my_data to a string first file.write(str(my_data)) And it works. But what if you want to read that file? with open('test_file.txt', 'r') as file: read_data = file.read() Now you have a problem, because your output is this string: "{'a': [1, 2, 3], 'b': {'foo': 'bar', 'baz': [4, 5, 6]}}" How do you convert a string into a dictionary? This here doesn't work: with open('test_file.txt', 'r') as file: read_data = dict(file.read()) Python by itself does not know how to convert a string into a dictionary. For that you need JSON. Also it makes sure that you meet all the conventions of the JSON format so that you can exchange data between different languages (e.g. from Python to JavaScript). The other thing is, if you have a .txt file, how would anybody know that this file contains a data structure without opening the file? If the file extension says "JSON" everybody knows how to interpret the data. Same with .XML, .HTML etc. Answer from MattR0se on reddit.com
🌐
Python
docs.python.org › 3 › library › json.html
json — JSON encoder and decoder
2 weeks ago - Serialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump(). ... Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings.
🌐
GeeksforGeeks
geeksforgeeks.org › python › json-dump-in-python
json.dump() in Python - GeeksforGeeks
January 13, 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.
Discussions

python - How do I write JSON data to a file? - Stack Overflow
Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size. More on stackoverflow.com
🌐 stackoverflow.com
Python json dump - Stack Overflow
Nothing to do with json, nor python. Because, when print() add a '\n' at the end, the dump to stdout doesn't More on stackoverflow.com
🌐 stackoverflow.com
json.dump with python.dump
How could I do this but have the language be python when it dumps? You can't. I need to do this because json does not read tuples and other things I am wanting to save into the file. So change them into lists. More on reddit.com
🌐 r/learnpython
27
1
August 1, 2023
`jsonable_encoder(obj)` vs `obj.model_dump(mode='json')`
I usually go with obj.model_dump_json() If I worried about performance I'd be using Go instead of Python More on reddit.com
🌐 r/FastAPI
4
4
October 6, 2024
🌐
Reddit
reddit.com › r/learnpython › why json.dump() and .load() are really needed?
r/learnpython on Reddit: Why json.dump() and .load() are really needed?
October 15, 2020 -

Hi, hope everyone is well.

Just nearing the basics end of PCC book, I'm at saving user's data now. What exactly is the reason, when storing simple data, to use json.dump() or load(), instead of just saving and then reading it from simple text file?

I just can't place it in my head why do I really need it and it always makes it more difficult for me to learn if that's the case.

Thank you all in advance.

Top answer
1 of 8
6
JSON data in python is essentially a dictionary (at least they are interchangeable, there are some minor differences with the formatting). Have you tried saving a dictionary to a simple text file? my_data = { 'a': [1, 2, 3], 'b': {'foo': 'bar', 'baz': [4, 5, 6]} } with open('test_file.txt', 'w') as file: file.write(my_data) This is not possible because Python expects a string that it can write to a file. It doesn't know how to turn a dictionary into something it can write to a file. But, maybe you then do this instead: my_data = { "a": [1, 2, 3], "b": {"foo": "bar", "baz": [4, 5, 6]} } with open('test_file.txt', 'w') as file: # cast my_data to a string first file.write(str(my_data)) And it works. But what if you want to read that file? with open('test_file.txt', 'r') as file: read_data = file.read() Now you have a problem, because your output is this string: "{'a': [1, 2, 3], 'b': {'foo': 'bar', 'baz': [4, 5, 6]}}" How do you convert a string into a dictionary? This here doesn't work: with open('test_file.txt', 'r') as file: read_data = dict(file.read()) Python by itself does not know how to convert a string into a dictionary. For that you need JSON. Also it makes sure that you meet all the conventions of the JSON format so that you can exchange data between different languages (e.g. from Python to JavaScript). The other thing is, if you have a .txt file, how would anybody know that this file contains a data structure without opening the file? If the file extension says "JSON" everybody knows how to interpret the data. Same with .XML, .HTML etc.
2 of 8
3
How would you structure the text file so that you can load the data later?
Top answer
1 of 16
3348

data is a Python dictionary. It needs to be encoded as JSON before writing.

Use this for maximum compatibility (Python 2 and 3):

import json
with open('data.json', 'w') as f:
    json.dump(data, f)

On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:

import json
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

See json documentation.

2 of 16
347

To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python 2 use:

import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
  f.write(json.dumps(data, ensure_ascii=False))

The code is simpler in Python 3:

import json
with open('data.txt', 'w') as f:
  json.dump(data, f, ensure_ascii=False)

On Windows, the encoding='utf-8' argument to open is still necessary.

To avoid storing an encoded copy of the data in memory (result of dumps) and to output utf8-encoded bytestrings in both Python 2 and 3, use:

import json, codecs
with open('data.txt', 'wb') as f:
    json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)

The codecs.getwriter call is redundant in Python 3 but required for Python 2


Readability and size:

The use of ensure_ascii=False gives better readability and smaller size:

>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'

>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17

Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.

🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
Find elsewhere
🌐
ReqBin
reqbin.com › code › python › pbokf3iz › python-json-dumps-example
How to dump Python object to JSON using json.dumps()?
To dump a Python object to JSON string, you can use the json.dumps() method of the built-in json module. The json.dump() paired method (without the "s") converts the Python object to JSON string and writes it to a file.
🌐
JSON for Modern C++
json.nlohmann.me › api › basic_json › dump
dump - JSON for Modern C++
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_object = {{"one", 1}, {"two", 2}}; json j_array = {1, 2, 4, 8, 16}; json j_string = "Hellö 😀!"; // call dump() std::cout << "objects:" << '\n' << j_object.dump() << "\n\n" << j_object.dump(-1) << "\n\n" << j_object.dump(0) << "\n\n" << j_object.dump(4) << "\n\n" << j_object.dump(1, '\t') << "\n\n"; std::cout << "arrays:" << '\n' << j_array.dump() << "\n\n" << j_array.dump(-1) << "\n\n" << j_array.dump(0) << "\n\n" << j_array.dump(4) << "\n\n" << j_array.dump(1, '\t') << "
🌐
ReqBin
reqbin.com › code › python › c6fxmvxt › python-dump-vs-dumps-example
What is the difference between json.dump() vs ...
July 27, 2023 - The json.dump() method converts a Python object into a JSON and writes it to a file, while the json.dumps() method encodes a Python object into JSON and returns a string. By default, json.dump() and json.dumps() generate minified versions of ...
🌐
PYnative
pynative.com › home › python › json › python json dump() and dumps() for json encoding
Python JSON dump() and dumps() for JSON Encoding
May 14, 2021 - Understand various use of json.dump() and dumps(). Encode Python objects into JSON and Write it in a file.
🌐
iProyal
iproyal.com › blog › json-dump-python
How to Use json.dump() in Python: A Beginner-Friendly Guide
May 19, 2025 - Using json.dump() is easy once you understand the basics. It helps you save JSON data safely and quickly. Using this function from the JSON module makes saving a Python object into a neat JSON file easier than you may think.
🌐
GitHub
github.com › nlohmann › json
GitHub - nlohmann/json: JSON for Modern C++ · GitHub
Note the library only supports UTF-8. When you store strings with different encodings in the library, calling dump() may throw an exception unless json::error_handler_t::replace or json::error_handler_t::ignore are used as error handlers.
Starred by 49.1K users
Forked by 7.3K users
Languages   C++ 96.9% | CMake 2.0% | Python 0.6% | Makefile 0.3% | Starlark 0.1% | Jinja 0.1%
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - You write JSON with Python using json.dump() to serialize data to a file.
🌐
Codecademy
codecademy.com › docs › python › json module › .dump()
Python | JSON Module | .dump() | Codecademy
May 29, 2025 - The .dump() function encodes a Python object as a JSON file. The process is known as serialization. The encoding conversion is based on this table.
🌐
JSON Formatter
jsonformatter.org › 9b6be4
Dump
It also provides a tree view that helps to navigate your formatted JSON data.