Question
How can I write JSON data stored in a Python dictionary named data to a file?
For example:
f = open('data.json', 'wb')
f.write(data)
This produces the following error:
TypeError: must be string or buffer, not dict
What is the correct way to save a Python dictionary as JSON in a file?
Short Answer
By the end of this page, you will understand why a Python dictionary cannot be written directly to a file as JSON, how to convert Python data into JSON text, and how to save it correctly using json.dump() and json.dumps(). You will also learn common mistakes, real-world usage patterns, and how this works in real Python projects.
Concept
A Python dict and JSON are closely related, but they are not the same thing.
- A Python dictionary is an in-memory Python object.
- JSON is a text format used to store and exchange structured data.
When you call:
f.write(data)
Python expects data to already be a string or bytes object. But data is a dictionary, so Python raises this error:
TypeError: must be string or buffer, not dict
To write JSON to a file, you must first serialize the dictionary. Serialization means converting a Python object into a format that can be stored or transmitted. In this case, the format is JSON text.
Python provides the built-in json module for this:
json.dump(obj, file)writes JSON directly to a file.json.dumps(obj)returns a JSON string.
This matters in real programming because JSON is everywhere:
- API responses
- configuration files
- logging structured data
- saving application state
- exporting data
If you understand the difference between Python objects and JSON text, file writing becomes much easier and less error-prone.
Mental Model
Think of a Python dictionary as a set of labeled containers in your program's memory.
data = {"name": "Ava", "age": 25}
That structure works well inside Python, but a file cannot store a live Python object directly. A file stores text or bytes.
JSON is like a written version of that dictionary that other programs can read:
{"name": "Ava", "age": 25}
So the process is:
- Start with a Python object.
- Convert it into JSON text.
- Write that text into a file.
A simple way to remember it:
dict= Python data structure- JSON = text representation of that structure
- file = place where the text is stored
Syntax and Examples
The most common and correct way to write a Python dictionary to a JSON file is with json.dump().
import json
data = {
"name": "Alice",
"age": 30,
"is_admin": False
}
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f)
What this does
import jsonloads Python's JSON module.open(..., 'w')opens the file for writing as text.json.dump(data, f)converts the dictionary to JSON and writes it to the file.
Writing pretty-formatted JSON
import json
data = {
"name": "Alice",
"age": 30,
"skills": ["Python", "SQL"]
}
with open('data.json', 'w', encoding='utf-8') f:
json.dump(data, f, indent=)
Step by Step Execution
Consider this example:
import json
data = {
"user": "sam",
"active": True
}
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f)
Step-by-step
-
import json- Python loads the JSON module.
-
data = {...}- A dictionary is created in memory.
- At this point, it is still a Python object, not JSON text.
-
open('data.json', 'w', encoding='utf-8')- Python opens
data.jsonin text write mode. - If the file does not exist, it is created.
- If it already exists, its contents are replaced.
- Python opens
-
with ... as f:- The file object is assigned to
f. - When the block finishes, Python automatically closes the file.
- The file object is assigned to
Real World Use Cases
Writing JSON files is common in many Python programs.
Saving configuration
Applications often store settings in JSON files:
config = {
"theme": "dark",
"autosave": True,
"font_size": 14
}
Exporting API data
If your script fetches data from an API, you may save the response for later:
import json
response_data = {
"status": "ok",
"results": [1, 2, 3]
}
with open('response.json', 'w', encoding='utf-8') as f:
json.dump(response_data, f, indent=2)
Logging structured results
Data-processing scripts often store summaries in JSON:
- number of records processed
- failed items
- timestamps
- performance metrics
Caching data
Programs sometimes save processed results to JSON so they do not need to recompute them every time.
Storing simple app state
Small tools and command-line apps often save user preferences or session state as JSON files because JSON is easy to read and edit.
Real Codebase Usage
In real projects, developers usually do more than just call json.dump().
Common pattern: use with open(...)
This ensures files are closed properly, even if an error occurs.
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f)
Common pattern: pretty-print for humans
When the file may be read by developers or users, indent is often used.
json.dump(data, f, indent=2)
Common pattern: preserve non-ASCII characters
json.dump(data, f, ensure_ascii=False, indent=2)
This is useful for names, languages, and international text.
Common pattern: validation before writing
Developers often check that required fields exist before saving.
def save_user(user):
if "id" user:
ValueError()
(, , encoding=) f:
json.dump(user, f, indent=)
Common Mistakes
Mistake 1: Writing a dictionary directly
Broken code:
data = {"a": 1}
with open('data.json', 'w', encoding='utf-8') as f:
f.write(data)
Why it fails:
f.write()expects a string.datais a dictionary.
Fix:
import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f)
Mistake 2: Opening the file in binary mode unnecessarily
Broken code:
with open('data.json', 'wb') as f:
json.dump(data, f)
Why it is a problem:
- JSON is typically written as text, not binary.
- Use
'w'instead of unless you have a very specific reason.
Comparisons
| Concept | What it does | Returns a value? | Best use case |
|---|---|---|---|
json.dump(data, file) | Writes JSON directly to a file | No | Saving JSON to disk |
json.dumps(data) | Converts data to a JSON string | Yes | When you need the JSON text first |
f.write(text) | Writes a string to a file | No | Writing plain text or an already-created JSON string |
str(data) | Converts a Python object to a Python-style string | Yes | Debugging, not JSON storage |
str(data) vs JSON
Cheat Sheet
import json
Write a dictionary to JSON file
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f)
Write pretty JSON
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
Get JSON as a string
json_text = json.dumps(data)
Write a JSON string manually
with open('data.json', 'w', encoding='utf-8') as f:
f.write(json.dumps(data))
Key rules
dictis not JSON textf.write()needs a string
FAQ
Why does f.write(data) fail in Python?
Because f.write() expects a string, but data is a dictionary. Convert it with json.dump() or json.dumps() first.
What is the difference between json.dump() and json.dumps()?
json.dump() writes JSON directly to a file. json.dumps() returns the JSON as a string.
Should I open a JSON file with 'w' or 'wb'?
Use 'w' for normal JSON writing in Python. JSON is usually handled as text.
How do I make the JSON file readable for humans?
Use the indent argument:
json.dump(data, f, indent=2)
Can I write a list to a JSON file too?
Yes. JSON supports arrays, so Python lists can also be written using json.dump().
Mini Project
Description
Build a small Python utility that saves a list of tasks to a JSON file. This demonstrates how Python dictionaries and lists can be serialized into JSON and written to disk in a format that is easy to inspect and reuse later.
Goal
Create a script that stores task data in a Python structure and writes it to a readable JSON file.
Requirements
- Create a Python dictionary containing a task list.
- Include at least one string, one boolean, and one list value.
- Write the data to a file named
tasks.json. - Format the JSON so it is easy for humans to read.
- Use
with open(...)and thejsonmodule.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.