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

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

Copyimport 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:

Copyimport 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
3351

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

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

Copyimport 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:

Copyimport 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:

Copyimport 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:

Copyimport 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:

Copyimport 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:

Copy>>> 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 would you use python to create JSON files?
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) More on reddit.com
🌐 r/learnpython
7
5
March 7, 2020
Proper way to open and write json files?
You should try to minimize file opening/closing operations. In general, the syntax to follow is: with open(FILENAME, MODE) as FILE_DESCRIPTOR_ALIAS: # DO OPERATIONS HERE MODE will determine the kinds of and behavior of input-output actions you can perform with the file. See this fantastic thread on the matter . So the typical workflow is: open a file, read in its contents, modify said contents, save the modified contents back to the file. The typical mode used for this kind of workflow is r+ More on reddit.com
🌐 r/learnpython
4
1
December 22, 2021
write json file to variable in python
JSON_DUMP = print(READFILE.read()) print() doesn't return anything, so by wrapping READFILE.read() here you're throwing away the file and returning None. Even if you had successfully saved the data, the json parameter of requests.post() expects a python object, not a string, so you'd probably want to have converted the file from a json string to a python object. You can do this like with open('state_info.txt') as f: data = json.load(f) r = requests.post(url=WEBHOOK, json=data) print(r.content) More on reddit.com
🌐 r/learnpython
31
0
August 24, 2023
formatting json output in Python
json.dumps(obj, indent=2, sort_keys=False) More on reddit.com
🌐 r/learnpython
16
52
May 12, 2022
🌐
Sentry
sentry.io › sentry answers › python › write json data to a file in python
Write JSON data to a file in Python | Sentry
with open("data.json", "r") as f: data = json.load(f) # will be { "firstname": "John", "lastname": "Doe", "age": 35 } ... Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski. SEE EPISODES ... David Y. — July 15, 2023 · Write a list to a file in Python with each item on a new line
🌐
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".
🌐
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
The following code serialises data ... as jsonfile: json.dump(data, jsonfile) To write your data to a string (and do something else with it later), use json.dumps()....
🌐
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 - The first step in writing JSON data to a file is to import the `json` module. This module contains methods for parsing and writing JSON data. ... - The `import` statement brings in the `json` module, which allows us to use its functions without ...
Find elsewhere
🌐
CCMC
ccmc.gsfc.nasa.gov › scoreboards › sep › writing-sepsb-json-guide
How to write your data to a JSON file | NASA CCMC
The best way to write your data to a JSON file is to load the JSON library for your language and use it to write out a JSON file. This is the best method to ensure that the JSON is properly formatted.
🌐
Python
docs.python.org › 3 › library › json.html
json — JSON encoder and decoder
Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this Python-to-JSON conversion table.
🌐
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 Global
February 6, 2024 - To store JSON data in a file, you can use the `json` module, which is part of the Python standard library.
🌐
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.
🌐
Scaler
scaler.com › home › topics › read, write, parse json file using python
Read, Write, Parse JSON File Using Python - Scaler Topics
April 17, 2024 - The json module in Python allows you to convert data structures to JSON strings using json.dumps() and provides a convenient way to write JSON data directly to a file using json.dump().
🌐
How Tos JSON
campbell-muscle-lab.github.io › howtos_json › pages › in_code › python › writing › writing.html
Writing JSON Files - How Tos JSON
# Import the json module for reading/writing JSONs. import json # Describe the file path where you would like to save the JSON file. JSON_FILE_PATH = "python_writing_demo.json" # Form the dictionary that we would like to write. Notice how close this syntax # is to the JSON structure!
🌐
DataCamp
datacamp.com › tutorial › json-data-python
Python JSON Data: A Guide With Examples | DataCamp
December 3, 2024 - import json import re with open('file_with_comments.json', 'r') as file: content = file.read() # Remove comments content = re.sub(r'//.*?$|/\*.*?\*/', '', content, flags=re.DOTALL | re.MULTILINE) data = json.loads(content) print(data) ... 101.2KIn this course, you'll learn the basics of relational databases and how to interact with them. ... 336.5KLearn to import data into Python from various sources, such as Excel, SQL, SAS and right from the web. ... Learn the different Python data types and how to use them effectively. ... Learn how to write to files in Python using built-in tools, common patterns, and best practices for real-world applications.
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
JSON is text, written with JavaScript object notation. Python has a built-in package called json, which can be used to work with JSON data.
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - With pretty_frieda.json as the value of the outfile option, you write the output into the JSON file instead of showing the content in the terminal. If the file doesn’t exist yet, then Python creates the file on the way.
🌐
iO Flood
ioflood.com › blog › python-write-json-to-file
Python Guide: How to Write JSON to a File
February 1, 2024 - In the above example, we have a dictionary with a key ‘children’ that contains a list of dictionaries. When we write this dictionary to a file using the json.dump() function, Python handles the nested data without any issues.
🌐
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