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.

🌐
GitHub
gist.github.com › Jxtopher › bbef0ef5f9ed19628d568eceb16883e6
[Python|json] Python save list of lists to file · GitHub
[Python|json] Python save list of lists to file. GitHub Gist: instantly share code, notes, and snippets.
Discussions

Storing list permanently and loading it in the exact same format
You can use writelines(). https://www.w3schools.com/python/ref_file_writelines.asp Besides that the proper way would be to convert to json and save, and load and convert it back. using json.dumps() and json.loads() https://realpython.com/python-json/ More on reddit.com
🌐 r/learnpython
8
3
January 20, 2023
python - Writing list of objects to JSON file - Stack Overflow
Save this question. Show activity on this post. As part of my homework I have to make a JSON file with class objects in it. More on stackoverflow.com
🌐 stackoverflow.com
python - Write a json file from list - Stack Overflow
My comment jumps around a bit, but the important thing here to actually solve the issue is to just write json.dump(data) to file. Let me know if that works though, I’m not entirely certain. I will try writing a proper answer with a better explanation later. ... Save this answer. More on stackoverflow.com
🌐 stackoverflow.com
How can I write data to a json file and also write the variable name?
The resulting file you are creating here isn't a valid json document. If you printed a "\n" between each dump, it would be valid jsonl (json lines). I believe just storing one data structure instead of 3 seperate ones solves both of your issues: import json my_data = { "x": [1, 2, 3], "y": [4, 5, 6], "z": {"1": 1, "2": 2}, } with open("test.json", "a", encoding="utf-8") as f: json.dump(my_data, f) More on reddit.com
🌐 r/learnpython
8
4
August 13, 2022
🌐
Blogboard
blogboard.io › blog › knowledge › how-to-write-a-list-to-a-file-in-python
How to Write a List to a File in Python
November 23, 2021 - We then call json.dump(cities, output_file, indent=2) to actually write the list to the file. The json.dump function has a number of useful parameters - here we've used indent=2 . It pretty-prints our json using 2 spaces as unit of indentation.
🌐
Reddit
reddit.com › r/learnpython › storing list permanently and loading it in the exact same format
r/learnpython on Reddit: Storing list permanently and loading it in the exact same format
January 20, 2023 -

I'm aiming to store a list of tickers permanently by writing it to a file that I can load when needed. Two things here:

  1. It's not working because readlines() interprets the file as one element and not a list of separate elements. I don't see a way to specify the separator between elements as comma.

  2. Making point 1 work should be very simple, but I'm surprised if code like what I have now (see below) is necessary. Seems so me that storing a list on disk and loading it in the exact same formatting should be a standard function. Is there something I'm overlooking?

My current code

Writing to file

file = open('TickerList.txt','w')
for item in items:
	file.write(item)
file.close()

Reading from file:

with open('TickerList.txt') as f:
ticker_list = f.readlines()
🌐
EyeHunts
tutorial.eyehunts.com › home › write list to json file python
Write list to JSON file Python - Tutorial - By EyeHunts
January 25, 2023 - def create_json(): json_string = json.dumps([ob.__dict__ for ob in stList]) with open("./data/student.txt", "w") as file: file.write(json_string) Do comment if you have any doubts or suggestions on this Python JSON file topic.
🌐
Python Examples
pythonexamples.org › python-write-json-to-file
Python Write JSON to File
In this example, we will convert or dump a Python Dictionary to JSON String, and write this JSON string to a file named data.json. import json aDict = {"a":54, "b":87} jsonString = json.dumps(aDict) jsonFile = open("data.json", "w") jsonFile.write(jsonString) jsonFile.close() Run the above program, and data.json will be created in the working directory. ... In this example, we will convert or dump Python List of Dictionaries to JSON string, and write this JSON string to file named data.json.
🌐
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.
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 - Now, let’s move on to how you can write JSON data to a file in Python. 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.
🌐
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
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert a python list to a json file
5 Best Ways to Convert a Python List to a JSON File - Be on the Right Side of Change
February 20, 2024 - This custom function save_list_as_json() takes a list and file name as arguments and uses json.dump() to serialize the list as JSON into the file. If you love Python’s one-liners, you can convert a list to a JSON file with a combination of list comprehension and file handling in a single line.
🌐
Javatpoint
javatpoint.com › save-json-file-in-python
Save JSON File in Python - Javatpoint
Save json File in Python with tutorial, tkinter, button, overview, canvas, frame, environment set-up, first python program, etc.
🌐
Medium
medium.com › @ryan_forrester_ › save-and-load-json-files-in-python-a-complete-guide-49a5760b8b49
Save and Load JSON Files in Python: A Complete Guide | by ryan | Medium
October 28, 2024 - Let’s explore how to work with them in Python, with clear examples you can use right away. Let’s start with the basics — saving a simple dictionary to a JSON file: import json # Your data user_data = { "name": "Alice Smith", "age": 28, "email": "alice@example.com", "interests": ["coding", "hiking", "photography"] } # Save to file with open("user_data.json", "w") as file: json.dump(user_data, file)
🌐
Quora
quora.com › How-do-you-save-data-to-a-JSON-file-using-Python
How to save data to a JSON file using Python - Quora
Answer: Any dictionary can be written to an opened file directly using the json.dump() function (don’t forget to import json beforehand), passing the dictionary as first argument and the opened file handle as second argument. There are some optional arguments as well for customization.
🌐
CodeRivers
coderivers.org › blog › python-save-json-to-file
Python Save JSON to File: A Comprehensive Guide - CodeRivers
February 22, 2026 - To use this module, you need to import it at the beginning of your Python script: ... To write JSON data to a file, you can use the json.dump() function. This function takes two required arguments: the JSON data to be written and the file object to which the data will be written.
🌐
IQCode
iqcode.com › code › javascript › python-save-list-to-json
python save list to json Code Example
October 2, 2021 - import json with open('data.json', 'w') as f: json.dump(data, f)
🌐
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 - If you encounter this edge-case, which has since been fixed in subsequent Python versions - try using json.dumps() instead, and write the string contents into a file instead of streaming the contents directly into a file.