Python Snippet

Read and Write JSON Files Idiomatically

Difficulty: Medium

Reading and writing JSON in Python is two lines once you know the right defaults. The right defaults are `with open(... encoding='utf-8')`, `json.load` / `json.dump` (not `loads` / `dumps`), and `indent=2, ensure_ascii=False` for human-readable files. This entry covers the round trip, atomic write, and the common pitfalls (bytes vs text mode, default ASCII escaping).

Code Snippets
/

Read and Write JSON Files Idiomatically

Read and Write JSON Files Idiomatically

Reading and writing JSON in Python is two lines once you know the right defaults. The right defaults are `with open(... encoding='utf-8')`, `json.load` / `json.dump` (not `loads` / `dumps`), and `indent=2, ensure_ascii=False` for human-readable files. This entry covers the round trip, atomic write, and the common pitfalls (bytes vs text mode, default ASCII escaping).

Python
Medium
3 snippets
file-io
py-standard-library
code-template

772 views

10

The standard recipe: open the file in text mode, hand the file object to json.dump (not dumps + manual write), and rely on with for cleanup. Always pass encoding='utf-8' explicitly; on Windows the platform default is not UTF-8 and you will hit mysterious decode errors otherwise. json.dump writes incrementally, so even multi-MB payloads do not need to build a giant string first. The tempfile.TemporaryDirectory() wrapper here is just for the runnable demo; in real code the path is whatever your config layer hands you.