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
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.

🌐
GeeksforGeeks
geeksforgeeks.org › python › reading-and-writing-json-to-a-file-in-python
Reading and Writing JSON to a File in Python - GeeksforGeeks
This process is called serialization. Let's explore two methods to write a JSON file in Python. The JSON package in Python has a function called json.dumps() that helps in converting a dictionary to a JSON object.
Published   August 5, 2025
🌐
Better Stack
betterstack.com › community › questions › how-to-write-json-data-to-file-in-python
How do I write JSON data to a file in Python? | Better Stack Community
import json data = { "name": "John ... that contains the JSON data. The dump() function takes two arguments: the JSON data and the file-like object to which the data should be written....
🌐
Python
docs.python.org › 3 › library › json.html
json — JSON encoder and decoder
2 weeks ago - Write the output of the infile to the given outfile. Otherwise, write it to sys.stdout. ... Sort the output of dictionaries alphabetically by key. Added in version 3.5. ... Disable escaping of non-ascii characters, see json.dumps() for more information.
🌐
ReqBin
reqbin.com › code › python › pbokf3iz › python-json-dumps-example
How to dump Python object to JSON using json.dumps()?
Python has a built-in module called json (JSON Encoder and Decoder) for working with JSON. To work with JSON in Python, you need to import the json module first. ... Serialization is the process of converting (encoding) Python objects into a stream of bytes (or string) to store the object in a database or file or transfer it over a network.
🌐
Sentry
sentry.io › sentry answers › python › write json data to a file in python
Write JSON data to a file in Python | Sentry
We can do this using Python’s built-in json library and file operations. Specifically, the json.dump function allows us to serialize a Python dictionary as JSON for writing to disk.
Find elsewhere
🌐
Medium
medium.com › @ryan_forrester_ › writing-json-to-a-file-in-python-a-step-by-step-guide-630584957d07
Writing JSON to a File in Python: A Step-by-Step Guide | by ryan | Medium
November 6, 2024 - - `with` statement: This ensures that the file is properly closed after its suite finishes, even if an error is raised. - `json.dump(data, json_file)`: This function takes two arguments: the data you want to write (in our case, the `data` ...
🌐
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.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-use-the-json-module-in-python
How to Use the JSON Module in Python – A Beginner's Guide
June 5, 2023 - The JSON module provides you with a json.dumps() function to serialize Python objects into a JSON formatted string. It provides various options for customization, including formatting the output to make it more human-readable.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-pretty-print-json
How to Pretty Print JSON in Python | DigitalOcean
September 16, 2025 - You’ll learn how to serialize custom Python objects, process massive JSON files without running out of memory, and leverage high-performance alternative libraries to speed up your applications. ... Use indent and sort_keys in json.dumps() to instantly make your JSON output readable and ...
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary · Built-in Modules Random Module Requests Module Statistics Module Math Module cMath Module · Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... JSON is a syntax for storing and exchanging data.
🌐
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 `encode_person` function is defined to handle instances of the `Person` class. The `default` parameter of `json.dump()` specifies this custom encoding function. In addition to storing data in a file, you may also need to generate JSON data from a Python dictionary.
🌐
Analytics Vidhya
analyticsvidhya.com › home › python json.loads() and json.dump() methods
Python json.loads() and json.dump() methods - Analytics Vidhya
May 1, 2025 - Python’s JSON.dump() function is used to serialize a Python object into a JSON-formatted string and write it to a file-like object. It inputs Python and file-like objects and writes the JSON data to the file.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python write json data to a file?
Python Write JSON Data to a File? - Spark By {Examples}
May 31, 2024 - We can use this method in combination with the write() method of a file object to write the JSON formatted string to a file. ... import json # Serialize the Python object to a JSON formatted string json_data = json.dumps(data) # Write the JSON ...
🌐
DataCamp
datacamp.com › tutorial › json-data-python
Python JSON Data: A Guide With Examples | DataCamp
December 3, 2024 - This function is used to serialize a Python object and write it to a JSON file. The dump() function takes two arguments, the Python object and the file object.
🌐
GeeksforGeeks
geeksforgeeks.org › python › json-dumps-in-python
json.dumps() in Python - GeeksforGeeks
The json.dumps() function in Python converts a Python object (such as a dictionary or list) into a JSON-formatted string. It is mainly used when you need to send data over APIs, store structured data or serialize Python objects into JSON text.
Published   January 13, 2026