Question

How to Write JSON Data to a File in Python

pythonjson

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:

  1. Start with a Python object.
  2. Convert it into JSON text.
  3. 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
Take Quiz

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 json loads 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') as f:
    json.dump(data, f, indent=2)

This creates a more readable file.

Using json.dumps() instead

import json

data = {
    "name": "Alice",
    "age": 30
}

json_string = json.dumps(data)

with open('data.json', 'w', encoding='utf-8') as f:
    f.write(json_string)

Use this when you specifically want the JSON as a string before writing it.

Example output

{
  "name": "Alice",
  "age": 30,
  "skills": [
    "Python",
    "SQL"
  ]
}

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

  1. import json

    • Python loads the JSON module.
  2. data = {...}

    • A dictionary is created in memory.
    • At this point, it is still a Python object, not JSON text.
  3. open('data.json', 'w', encoding='utf-8')

    • Python opens data.json in text write mode.
    • If the file does not exist, it is created.
    • If it already exists, its contents are replaced.
  4. with ... as f:

    • The file object is assigned to f.
    • When the block finishes, Python automatically closes the file.
  5. json.dump(data, f)

    • Python converts the dictionary into JSON text.
    • That JSON text is written directly into the file.

Resulting file content

{"user": "sam", "active": true}

Notice an important detail:

  • Python True becomes JSON true
  • Python dictionaries become JSON objects

That conversion is handled automatically by the json module.

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.

Take Quiz

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" not in user:
        raise ValueError("user must contain an 'id'")

    with open('user.json', 'w', encoding='utf-8') as f:
        json.dump(user, f, indent=2)

Common pattern: error handling

import json

try:
    with open('data.json', 'w', encoding='utf-8') as f:
        json.dump(data, f)
except OSError as e:
    print(f"File error: {e}")
except TypeError as e:
    print(f"JSON serialization error: {e}")

This helps when:

  • the path is invalid
  • permissions are missing
  • the data contains unsupported types

Common pattern: helper function

In larger codebases, file-writing logic is often wrapped in a reusable function.

import json

def save_json(path, data):
    with open(path, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2)

This keeps code consistent across the project.

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.
  • data is 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 'wb' unless you have a very specific reason.

Fix:

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f)

Mistake 3: Confusing dump() and dumps()

  • json.dump(data, file) writes to a file
  • json.dumps(data) returns a string

Broken code:

with open('data.json', 'w', encoding='utf-8') as f:
    json.dumps(data)

Why it is wrong:

  • The JSON string is created but never written anywhere.

Fix:

with open('data.json', 'w', encoding='utf-8') as f:
    f.write(json.dumps(data))

Or better:

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f)

Mistake 4: Trying to serialize unsupported objects

Broken code:

import json
from datetime import datetime

data = {"created": datetime.now()}

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f)

Why it fails:

  • Some Python objects are not JSON serializable by default.

Possible fix:

data = {"created": datetime.now().isoformat()}

Mistake 5: Forgetting that writing mode overwrites the file

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f)

This replaces existing content. If you want to update existing JSON, you usually need to:

  1. read the file
  2. modify the data
  3. write the full JSON back

Comparisons

ConceptWhat it doesReturns a value?Best use case
json.dump(data, file)Writes JSON directly to a fileNoSaving JSON to disk
json.dumps(data)Converts data to a JSON stringYesWhen you need the JSON text first
f.write(text)Writes a string to a fileNoWriting plain text or an already-created JSON string
str(data)Converts a Python object to a Python-style stringYesDebugging, not JSON storage

str(data) vs JSON

data = {"name": "Ana", "active": True}

str(data) gives:

{'name': 'Ana', 'active': True}

This is not valid JSON because:

  • it uses single quotes
  • it uses True instead of true

json.dumps(data) gives:

{"name": "Ana", "active": true}

This is valid JSON.

Text mode vs binary mode

File modeMeaningTypical JSON usage
'w'Write textRecommended
'wb'Write bytesUsually unnecessary for JSON
'a'Append textRare for full JSON documents

with open() vs manual close

ApproachBenefit
with open(...) as f:Safer, automatically closes file
f = open(...); ...; f.close()Works, but easier to forget close()
Take Quiz

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

  • dict is not JSON text
  • f.write() needs a string
  • json.dump() writes to a file
  • json.dumps() returns a string
  • Use 'w' for JSON text files
  • Prefer with open(...)

Common options

json.dump(data, f, indent=2, ensure_ascii=False)

Common error

TypeError: must be string or buffer, not dict

Meaning:

  • you tried to write a dictionary directly instead of converting it to JSON first

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().

Why is str(my_dict) not the same as JSON?

str(my_dict) creates a Python-style string representation, not valid JSON. JSON uses double quotes and JSON-specific values like true, false, and null.

What kinds of Python objects can JSON handle?

Common supported types include:

  • dict
  • list
  • str
  • int
  • float
  • bool
  • None

Some objects like datetime need conversion first.

Does writing JSON overwrite the file?

Yes, if you open the file with 'w', existing contents are replaced.

Take Quiz

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

  1. Create a Python dictionary containing a task list.
  2. Include at least one string, one boolean, and one list value.
  3. Write the data to a file named tasks.json.
  4. Format the JSON so it is easy for humans to read.
  5. Use with open(...) and the json module.
Take Quiz

Keep learning

Related questions

View more