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.

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

How to transform a JSON file into a CSV one in Python?
Hi Everyone, I have a quick question. Thanks to a previous post : Python: Extract Data from an Interactive Map on the Web, with Several Years, into a CSV file I was been able to extract JSON data from the web. Thanks again to @FelixLeg & @kknechtel to their useful help and advices. More on discuss.python.org
🌐 discuss.python.org
0
April 8, 2024
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
python - Reading JSON from a file - Stack Overflow
When looking at a hierarchic json ... something present. The distinction between undefined and empty is not always going to be made clear in JSON files. For example, several popular non-python librariesl convert empty lists (and empty dicts) into JSON null.... More on stackoverflow.com
🌐 stackoverflow.com
One Horse Sized JSON file or 1000 Duck Sized JSON files.
Just put it in a database like SQLite. More on reddit.com
🌐 r/Python
45
64
November 12, 2020
🌐
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 - This is particularly useful when you need to save the state of your program or share data with other applications. To store JSON data in a file, you can use the `json` module, which is part of the Python standard library.
🌐
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 - In Python, working with JSON is straightforward thanks to the built-in `json` module. This article will guide you through the process of writing JSON to a file in Python with detailed explanations and practical code examples, making it easy for novice learners to grasp the concept.
🌐
HackerNoon
hackernoon.com › how-to-read-and-write-json-files-in-python
How to read and write JSON files in Python | HackerNoon
March 19, 2024 - We will discuss how to use Python to read, write, and manipulate JSON files.
🌐
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.
🌐
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
Find elsewhere
🌐
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.
🌐
Python.org
discuss.python.org › python help
How to transform a JSON file into a CSV one in Python? - Python Help - Discussions on Python.org
April 8, 2024 - Hi Everyone, I have a quick question. Thanks to a previous post : Python: Extract Data from an Interactive Map on the Web, with Several Years, into a CSV file I was been able to extract JSON data from the web. Thank…
🌐
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".
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
Python has a built-in package called json, which can be used to work with JSON data.
🌐
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
docs.python.org › 3 › library › json.html
json — JSON encoder and decoder
2 weeks ago - Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this Python-to-JSON conversion table.
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - 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.
🌐
W3Schools
w3schools.com › python › gloss_python_convert_into_JSON.asp
Python Convert From Python to JSON
Python JSON Tutorial JSON Parse JSON Format JSON Sort JSON ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
🌐
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.
🌐
Zyte
zyte.com › home › blog › json parsing with python [practical guide]
A Practical Guide to JSON Parsing with Python
July 6, 2023 - Saving JSON to a file using json.dump() and with open() context manager with write mode setting (writing mode "w"): ... When traversing JSON data in Python, depending on the complexity of the object, there are more advanced libraries to help ...
🌐
LearnPython.com
learnpython.com › blog › json-in-python
How to Convert a String to JSON in Python | LearnPython.com
Files that store data in JSON format are called JSON files. These files are text-based, human-readable, and easy to process – all of which make them highly popular. In this article, we will learn how to convert a string to JSON in Python and how to create JSON files from Python objects.
🌐
GeeksforGeeks
geeksforgeeks.org › python › read-json-file-using-python
Read JSON file using Python - GeeksforGeeks
We will be using Python’s json module, which offers several methods to work with JSON data. In particular, loads() and load() are used to read JSON from strings and files, respectively.
Published   September 15, 2025