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.

Answer from phihag on Stack Overflow
🌐
Python
docs.python.org › 3 › library › json.html
json — JSON encoder and decoder
2 weeks ago - In JSON, an object refers to any data wrapped in curly braces, similar to a Python dictionary. ... Be cautious when parsing JSON data from untrusted sources. A malicious JSON string may cause the decoder to consume considerable CPU and memory resources. Limiting the size of data to be parsed is recommended. This module exposes an API familiar to users of the standard library marshal and pickle modules. ... >>> import json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print(json.dumps("\"foo\bar")) "\"foo\bar" >>> print(json.dumps('\u1234')) "\u1234" >>> print(json.dumps('\\')) "\\" >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)) {"a": 0, "b": 0, "c": 0} >>> from io import StringIO >>> io = StringIO() >>> json.dump(['streaming API'], io) >>> io.getvalue() '["streaming API"]'
🌐
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
Basically, I think it's a bug in the json.dump() function in Python 2 only - It can't dump a Python (dictionary / list) data containing non-ASCII characters, even you open the file with the encoding = 'utf-8' parameter. (i.e. No matter what you do). More on stackoverflow.com
🌐 stackoverflow.com
Why json.dump() and .load() are really needed?
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. More on reddit.com
🌐 r/learnpython
18
8
October 15, 2020
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 7, 2024
🌐
Quora
quora.com › In-Python-what-do-json-dump-and-json-load-do
In Python, what do json.dump and json.load do? - Quora
Answer (1 of 3): json is a data transfer mechanism - originally it was design as part of the Java and Javascript environment but JSON is now widely used in many places. json defines a number of different data types : integer, float, string, and also lists and dictionaries. The nice thing about ...
🌐
Leapcell
leapcell.io › blog › understanding-json-dumps-in-python
Understanding `json.dumps()` in Python | Leapcell
July 25, 2025 - The json.dumps() function in Python is used to convert a Python object into a JSON-formatted string.
🌐
Python documentation
docs.python.org › 3 › tutorial › inputoutput.html
7. Input and Output — Python 3.14.3 documentation
Another variant of the dumps() function, called dump(), simply serializes the object to a text file. So if f is a text file object opened for writing, we can do this: ... To decode the object again, if f is a binary file or text file object which has been opened for reading: ... JSON files must be encoded in UTF-8.
🌐
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.
Find elsewhere
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.

🌐
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?
🌐
Code Institute
codeinstitute.net › blog › python › working with json in python: a beginner’s guide
Working with JSON in Python: A Beginner's Guide - Code Institute DE
February 6, 2024 - In this example, the `json.dumps()` function converts the Python dictionary (`person`) into a JSON-formatted string (`json_data`), which can be printed or used as needed.
🌐
ReqBin
reqbin.com › code › python › pbokf3iz › python-json-dumps-example
How to dump Python object to JSON using json.dumps()?
The json module provides an extensible ... JSON data strings into Python objects. The JSON dump method takes an optional cls parameter to pass your own JSON encoder implementation....
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python json.dump() function
Python json.dump() Function - Spark By {Examples ...
May 31, 2024 - json.dump() is a built-in function from json module that is used to encode Python objects as JSON strings and write them to a file-like object. You can
🌐
Tutorialspoint
tutorialspoint.com › python › json_dump_function.htm
Python json.dump() Function
The Python json.dump() function is used to serialize a Python object into a JSON formatted string and write it to a file. This function is useful when storing data in JSON format, such as saving configurations, logging structured data, or exporting
🌐
Bogotobogo
bogotobogo.com › python › python-json-dumps-loads-file-read-write.php
Python Tutorial: json.dump(s) & json.load(s) - 2024
import socket import json import sys HOST = 'demo-NLB-.....elb.us-west-2.amazonaws.com' PORT = 6514 try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as error: if error.errno == errno.ECONNREFUSED: print(os.strerror(error.errno)) else: raise try: sock.connect((HOST, PORT)) except socket.error as error: if error.errno == errno.ECONNREFUSED: print(os.strerror(error.errno)) else: raise msg = {'@message': 'May 11 10:40:48 scrooge disk-health-nurse[26783]: [ID 702911 user.error] m:SY-mon-full-500 c:H : partition health measures for /var did not suffice - still using 96% of partition space', '@tags': ['python', 'test']} sock.send(json.dump
🌐
Board Infinity
boardinfinity.com › blog › json-dump
json.dumps in Python | Board Infinity
August 9, 2025 - Learn how to use json.dumps in Python to convert Python objects into JSON format, with syntax, parameters, and practical examples.
🌐
Board Infinity
boardinfinity.com › blog › json-file-in-python
JSON file in Python: Read and Write | Board Infinity
January 3, 2025 - json.dumps() is the JSON data serialization method in Python that converts a Python object to a JSON Object.
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - To investigate how to load a Python dictionary from a JSON object, revisit the example from before. Start by creating a dog_registry dictionary and then serialize the Python dictionary to a JSON string using json.dumps():
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-pretty-print-json
How to Pretty Print JSON in Python | DigitalOcean
September 16, 2025 - Learn how to pretty print JSON in Python using built-in tools like json.dumps() and pprint to improve readability and debug structured data efficiently.
🌐
Medium
medium.com › data-science › you-must-know-python-json-dumps-but-maybe-not-all-aspects-fa8d98a76aa0
You Must Know Python JSON Dumps, But Maybe Not All Aspects | by Christopher Tao | TDS Archive | Medium
December 6, 2021 - Python has built-in support to ... have used it a lot. We know that we can use the json.dumps() method to easily convert a Python dictionary object into a JSON string....
🌐
Codereview
codereview.doctor › features › python › best-practice › write-json-file-json-dump
Use json.dump to write JSON to file best practice | codereview.doctor
json.dumps is for JSON serialising an object to a string, while json.dump (no "s") is for JSON serialising an object to a file.