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
3357

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
Discussions

How do i save what i write in here to a json file?
How do i save what i write in here to a json file · If you want all of the text, give the start index as '1.0' (line 1, column 0) and the end index as 'end' · Note that after root.mainloop() returns, the widget won’t exist any longer, so here I’m getting it when the window closes: More on discuss.python.org
🌐 discuss.python.org
2
0
February 6, 2025
saving a JSON file in python - Stack Overflow
I have made some changes to a JSON file in python by using numpy and pandas. I have successfully made the desired changes as I can see through print() function, but I am unable to save the changes ... More on stackoverflow.com
🌐 stackoverflow.com
How would you use python to create JSON files?
From StackOverflow JSON is basically a way of communicating data to someone, with very specific rules. Using Key Value Pairs and Arrays. JSON is very lightweight and is a nice way to store information. If you request a web-server, most responses will be in JSON format. Example of JSON data (also from StackOverflow): { "first_name": "John", "last_name": "Smith", "address": { "street_address": "21 2nd Street", "city": "New York", "state": "NY", "postal_code": 10021 }, "phone_numbers": [ "212 555-1234", "646 555-4567" ] } Now, to answer your question. How to create JSON files using Python? First, you need valid JSON in your Python code. images = [ { "name": "awesome_image.png", "file_size": 1240000, "file_type": "image/png", }, { "name": "good_image.jpg", "file_size": 742600, "file_type": "image/jpeg" } ] Now, using the json library # Load data. This will transform the data into an indented string. json_data = json.dumps(images, indent=2) # Create and write to file. with open("/home/user/Documents/images.json", "w") as json_file: json_file.write(json_data) How to load JSON files in Python? # Open file in read mode. with open("/home/user/Documents/images.json", "r") as f: # We can do this in two ways. # 1. Load file directly. data = json.load(f) # 2. Load from the file's contents. data = json.loads(f.read()) Now all the file content is stored in the data variable. If you are dealing with files, it's better to load and work with them in Python. It'll be faster than to keep opening and closing files all the time. Create functions to write/load files and use them when you need to. More on reddit.com
🌐 r/learnpython
7
5
March 7, 2020
How to save to a json file
Hey I am trying to have you enter a phrase into an input tag in html, and then when you press an enter button it saves the phrase to a json file. I think I could use python to do this, but don’t know how. More on discuss.python.org
🌐 discuss.python.org
3
0
January 3, 2024
🌐
Sentry
sentry.io › sentry answers › python › write json data to a file in python
Write to JSON File in Python Using json.dump() | Sentry
July 3, 2026 - Use Python's built-in json.dump() to serialize dictionaries to JSON files with formatting options like indent and sort_keys, plus json.load() to read them back
🌐
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
It offers simple functions to convert between Python objects and JSON. 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.org
discuss.python.org › python help
How do i save what i write in here to a json file? - Python Help - Discussions on Python.org
February 6, 2025 - How do i save what i write in here to a json file · If you want all of the text, give the start index as '1.0' (line 1, column 0) and the end index as 'end' · Note that after root.mainloop() returns, the widget won’t exist any longer, so here I’m getting it when the window closes:
🌐
YouTube
youtube.com › watch
How to Save and Load Data in Python Using JSON Files | Python JSON Module - YouTube
💻 *Get my Source Codes and support the channel* ❤️: https://www.buymeacoffee.com/fabiomusanni/extras⬇️ *LEARN ON THE BEST LEARNING PLATFORMS (LINKS BELOW)* ...
Published: August 10, 2022
Find elsewhere
🌐
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 - To store JSON data in a file, you can use the `json` module, which is part of the Python standard library. Let’s consider a simple example where we have a Python dictionary representing a person, and we want to store this data in a JSON file:
🌐
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 - Writing JSON to a file in Python is a simple and effective way to store data. By using the `json` module, you can easily convert Python dictionaries to JSON format and save them for later use.
🌐
OneUptime
oneuptime.com › home › blog › how to read and write json files in python
How to Read and Write JSON Files in Python
January 25, 2026 - JSON (JavaScript Object Notation) is a lightweight, human-readable format that maps naturally to Python dictionaries and lists. Python's built-in json module makes it straightforward to parse JSON from files and strings, as well as serialize Python objects back to JSON.
🌐
Imperial College London
python.pages.doc.ic.ac.uk › java › lessons › java › 10-files › 04-dump.html
Python for Java Programmers > Writing to JSON files | Department of Computing | Imperial College London
Conversely, you can also easily write a Python object to a JSON string. The fancy term is serialisation (converting a data object into a string representation, usually for storage or transmission). To write your data into a JSON file, use json.dump(). The following code serialises data to JSON format and saves it in a file called output.json.
🌐
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
You can use the json module in Python to write JSON data to a file. The module has a dump() function that can be used to write JSON data to a file-like object.
🌐
Board Infinity
boardinfinity.com › blog › json-file-in-python
JSON file in Python: Read and Write | Board Infinity
January 3, 2025 - Most Python applications read and write their configurations from JSON files because JSON is easy to edit. You can load the configuration and see it in the program as well as change it and save it back to a JSON file.
🌐
CCMC
ccmc.gsfc.nasa.gov › scoreboards › sep › writing-sepsb-json-guide
How to write your data to a JSON file | NASA CCMC
If you use a different language, you can google ' write json file' and get the steps to do that in your programming language. You can download the helper script (sep_json_writer.py) here (last updated on 2021.08.11).
🌐
Vertabelo Academy
academy.vertabelo.com › course › python-json › writing-json-files › writing-to-json-file › convert-a-string-into-a-json-file
How to Read and Write JSON Files in Python | Learn Python | Vertabelo Academy
Remember, json.dumps() converts the given data to a string. The json.dump() function writes that data to a specified file. Save the data variable in JSON format to a file named personal_data.json.
🌐
Python.org
discuss.python.org › python help
How to save to a json file - Python Help - Discussions on Python.org
January 3, 2024 - Hey I am trying to have you enter a phrase into an input tag in html, and then when you press an enter button it saves the phrase to a json file. I think I could use python to do this, but don’t know how.
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
July 21, 2026 - Learn how to work with JSON data in Python using the json module. Convert, read, write, and validate JSON files and handle JSON data for APIs and storage.
🌐
Opensource.com
opensource.com › article › 19 › 7 › save-and-load-data-python-json
Save and load Python data with JSON | Opensource.com
This function implements the inverse, more or less, of saving the file: an arbitrary variable (f) represents the data file, and then the JSON module’s load function dumps the data from the file into the arbitrary team variable.