pythonjsonformatter

Write a Python dict to a JSON file

json.dump() writes the dictionary straight to a file. json.dumps() returns a string and does not create the file for you.

Write the dict with json.dump()

To save a dict as JSON, or to write a dictionary to a JSON file, open a text file and pass it to json.dump(). The function writes JSON. It does not write Python syntax.

import json

data = {"project": "formatter", "published": True, "city": "Madrid"}

with open("data.json", "w", encoding="utf-8") as file:
    json.dump(data, file, indent=2, ensure_ascii=False)

The file contains JSON values, not Python spellings: True becomes true. Opening with "w" replaces an existing file of the same name, so choose the path deliberately.

{
  "project": "formatter",
  "published": true,
  "city": "Madrid"
}

Formatting decisions

indent=2 makes a file easier to review in a code editor. ensure_ascii=False keeps supported Unicode characters readable instead of escaping them. Use sort_keys=True only when stable key ordering helps reviews or reproducible output.

NeedOption
Readable nested JSONindent=2
Readable Unicode textensure_ascii=False
Stable orderingsort_keys=True

Read the same file back

with open("data.json", encoding="utf-8") as file:
    restored = json.load(file)

assert restored == data
print(restored["published"])  # True

Replace the file only after a successful write

Opening with "w" truncates the destination immediately. If json.dump() then raises, the previous file is already gone. Write a sibling file and replace the destination after serialization returns:

import json
import os

data = {"project": "formatter", "published": True}

temporary = "data.json.tmp"
with open(temporary, "w", encoding="utf-8") as file:
    json.dump(data, file, indent=2, ensure_ascii=False)
    file.write("\n")
os.replace(temporary, "data.json")

os.replace() overwrites data.json only after the temporary file is complete. If json.dump() raises, the original file is untouched and the .tmp file may still be there. Delete that leftover yourself if you retry. A value that is not JSON-serializable still has to be converted first; see serialization errors. To load this file later, use json.load().

Exporting one record per line? Follow the JSON Lines reader and writer instead of concatenating JSON documents. For escaped characters or damaged text, see Unicode escapes and file encoding.

By Python JSON Formatter ·