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
It takes two parameters: dictionary: ... indentation · After converting the dictionary to a JSON object, simply write it to a file using the "write" function....
Published   August 5, 2025
🌐
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` ...
🌐
Reddit
reddit.com › r/learnpython › how would you use python to create json files?
r/learnpython on Reddit: How would you use python to create JSON files?
March 7, 2020 -

Howdy!

I recently took a coding test for an internship program, I was quickly put in check by the coding test. I am only about 50 hours into coding, but I had higher hopes for myself then how I performed.

The questions that tripped me up were how to take input in the form of a Dict [] and create a JSON object out of it. I was allowed to read documentation during the test and found the JSON library with json.dumps, but couldn't figure out how to use it in the allotted time. =^(

In the spirit of improvement would you fine folks of r/learnpython be willing to show how you would create a JSON object with python, and outline some reasons as to why you would want to create a JSON object in the first place? I'm hoping to learn something new, but I also hope that there are a few on this sub who can come across the post and learn something new too.

On the bright side, I solved FizzBuzz no problem. That problem gave me anxiety when I first started coding, and now I can solve it expertly. Little wins!

Thank you! =^)

Top answer
1 of 4
5
I read two concrete questions from your post: why you would want to create a JSON object Imagine you want multiple software systems to communicate. Let's say we have three systems, one written in Python, one client written in JavaScript and one more backend system in Java. You can't just send Python objects over a network and expect the systems written in JS or Java to understand them. Same thing the other way around. In the end it's just electrical signals and both the sender and receiver need a common understanding of how to interpret those signals, otherwise they will just be gibberish. That's where data formats like JSON come into play: It's a simple and standardized data format that can be handled in any modern programming language. Now your Python code can serialize its internal representation of a piece of data into this format and send it over a network or store it on some disk, where some other system will eventually pick it up, deserialize it into its own internal representation and process it. show how you would create a JSON object with python import json data = {"year": 2020, "sales": 12345678, "currency": "€"} # creating a JSON string json_string = json.dumps(data) # storing it in a file with open("data.json", "w") as json_file: json.dump(data, json_file)
2 of 4
3
If you know about the JSON library, there's not much more to tell. RealPython have excellent tutorials and information. https://realpython.com/python-json/ You can find a lot more by searching "python json tutorial".
🌐
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
The dump() function takes two arguments: the JSON data and the file-like object to which the data should be written. The with open statement opens the file "data.json" in "w" mode, which means it will be opened for writing.
🌐
Reddit
reddit.com › r/learnpython › need help understanding how to write a file to json (python) without overwriting it
r/learnpython on Reddit: need help understanding how to write a file to json (python) without overwriting it
October 4, 2022 -
My Code:  Python, (Using discord rewrite if this matters)

user_id = str(ctx.message.author.id)
        print(user_id)

        # reads data
        with open("test.json", "r") as f:
            data = json.load(f)
            print(data)
            print(type(data))

            # checks if user is in data
            if user_id not in data['users'].__str__():
                data.update({})
                print(data)

                # checks if data is type list
                if type(data) is dict:
                    data = [data]
                    print(type(data))

                # updates data with new user
                data.append({"user_id": user_id})
                print(data)
                
                # writes new data to json file
                with open("test.json", "w"):
                    json.dump(data, f)

Error Code:  Command raised an exception: UnsupportedOperation: not writable
Find elsewhere
🌐
Board Infinity
boardinfinity.com › blog › json-file-in-python
JSON file in Python: Read and Write | Board Infinity
January 3, 2025 - When you have either modified or created Python data including a dictionary or list, you might wish to write this data back to a JSON file. The json.dump() function is another function in JSON that enables the writer to serialize and write Python ...
🌐
Python Examples
pythonexamples.org › python-write-json-to-file
Python Write JSON to File
You can convert any Python object to a JSON string and write JSON to File using json.dumps() function and file.write() function respectively.
🌐
CodeSignal
codesignal.com › learn › courses › hierarchical-and-structured-data-formats › lessons › constructing-objects-and-writing-to-json-files
Constructing Objects and Writing to JSON Files
To write our data to a JSON file, we'll use the json.dump() function, which serializes Python objects into JSON format and writes it to a file.
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.3 documentation
Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this Python-to-JSON conversion table.
🌐
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.
🌐
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.
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - You can write JSON with Python by using the json.dump() function to serialize Python objects into a JSON file.
🌐
Stack Abuse
stackabuse.com › reading-and-writing-json-to-a-file-in-python
Reading and Writing JSON to a File in Python
April 18, 2023 - json.dump() - Serialized an object into a JSON stream for saving into files or sockets · Note: The "s" in "dumps" is actually short for "dump string". JSON's natural format is similar to a map in computer science - a map of key-value pairs. In Python, a dictionary is a map implementation, so we'll naturally be able to represent JSON faithfully through a dict.
🌐
Programiz
programiz.com › python-programming › json
Python JSON: Read, Write, Parse JSON (With Examples)
Here's a table showing Python objects and their equivalent conversion to JSON. To write JSON to a file in Python, we can use json.dump() method.
🌐
Python.org
discuss.python.org › python help
Appending JSON to same file - Python Help - Discussions on Python.org
January 5, 2023 - Hi, I need to make that within each request from api new dict will be appended to json. Now I have that each time data overwritten, but I need to append to existing file. How to achieve this? Code:(import requestsimpor…
🌐
Simplilearn
simplilearn.com › home › resources › software development › json python: read, write, and parse json files in python
JSON Python: Read, Write, and Parse JSON Files in Python
October 11, 2022 - JSON, short for JavaScript object notation, is a syntax for storing and exchanging data. Learn how to write JSON to a file and convert from python to JSON now!
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
W3Schools
w3schools.com › PYTHON › python_json.asp
Python JSON
Convert a Python object containing all the legal data types: import json x = { "name": "John", "age": 30, "married": True, "divorced": False, "children": ("Ann","Billy"), "pets": None, "cars": [ {"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1} ] } print(json.dumps(x)) Try it Yourself » · The example above prints a JSON string, but it is not very easy to read, with no indentations and line breaks.