json.dump
Write a Python object to an open file in JSON format.
Python 3.13
json.dump(obj, fp, *, ensure_ascii=True, indent=None, sort_keys=False)Parameters
- objAny
- The object to write: a dict, list, tuple, string, number, bool or None.
- fpTextIO
- A file open for writing in text mode, such as open('data.json', 'w', encoding='utf-8'), or io.StringIO.
- ensure_asciibooloptional
- If False, non-ASCII characters are written as is instead of \uXXXX escapes.
- indentint | str | Noneoptional
- The indentation for nested items; if given, the JSON spans several lines.
- sort_keysbooloptional
- If True, dictionary keys are sorted.
Return value
Nothing (None); the JSON is written to the file.
Examples
Writing a dictionary to a file
Python 3.13
import json
data = {'name': 'Anna', 'langs': ['Python', 'SQL']}
with open('user.json', 'w', encoding='utf-8') as file:
json.dump(data, file)
with open('user.json', encoding='utf-8') as file:
print(file.read()){"name": "Anna", "langs": ["Python", "SQL"]}Cyrillic text and indentation in io.StringIO
Python 3.13
import io
import json
buffer = io.StringIO()
json.dump({'city': 'Москва'}, buffer, ensure_ascii=False, indent=2)
print(buffer.getvalue()){
"city": "Москва"
}Details
Unlike json.dumps, it does not return a string but writes it straight to the file. Open the file in 'w' mode with encoding='utf-8', especially together with ensure_ascii=False. A second call for the same open file appends another object, and such a file can no longer be read with json.load.
