How can I save Python data as readable, indented JSON?
Quick answer
Use Python’s json module to write your data to a separate output file opened in text mode with UTF-8 encoding. Pass indent=2 to json.dump to make the JSON easier to read. Then open that output file and use json.load to read it back. Choose an output filename that is not your source sample: opening a file in write mode erases its existing contents. [S1] [S2]
The question, the details, the next step.
A practical checklist
Import Python’s
jsonmodule.Choose an output filename distinct from the source sample you want to preserve.
Open the output in text write mode with
encoding="utf-8".Call
json.dump(data, file, indent=2)for readable formatting.Reopen that output with UTF-8 encoding and use
json.loadto read it back.
A few more useful answers
Does `indent=2` change the data?
It controls the JSON’s formatting by adding indentation and line breaks for readability. [S1]
Why use a separate output filename?
What does the reload check tell me?
json.load reads JSON from a file object and returns the decoded Python value. It shows that the output can be loaded; it does not compare that value with a separate expected result. [S2]
Sources
References used for this guide.
- [S1] Python 3.15.2 Library Reference: json — JSON encoder and decoder docs.python.org · Checked
- [S2] Python Tutorial, section 7.2: Saving structured data with json docs.python.org · Checked
