Python Basics: Reading and Writing JSON Files
JSON is useful for small configuration files and data exchanged between programs. Python’s standard-library json module converts JSON into dictionaries, lists, and other Python values.
These examples use Python 3 on Linux. Run the shell commands in order in the same shell. Start in a fresh temporary directory so the example filenames cannot overwrite your work:
cd "$(mktemp -d)"Read a JSON file
Create a small practice file, then read it:
printf '{"name": "demo", "retries": 2, "enabled": true}\n' > settings.jsonSave as demo_json_1.py:
import json
with open("settings.json", encoding="utf-8") as file:
settings = json.load(file)
print(settings["name"])
print(settings["retries"] + 1)
print(settings["enabled"])Run:
python3 demo_json_1.pyOutput:
demo
3
TrueThe JSON object becomes a dictionary. The number stays numeric, and JSON true becomes Python True. The with block closes the file after reading it.
Write an updated copy
This creates updated.json. Mode "w" replaces its contents if it already exists, so use only the practice directory.
Save as demo_json_2.py:
import json
with open("settings.json", encoding="utf-8") as file:
settings = json.load(file)
settings["retries"] = 3
with open("updated.json", "w", encoding="utf-8") as file:
json.dump(settings, file)
file.write("\n")Run:
python3 demo_json_2.py
cat updated.jsonOutput:
{"name": "demo", "retries": 3, "enabled": true}json.dump() writes to a file. json.dumps() instead returns a string; the corresponding reading functions are load() and loads().
Handle invalid input
JSON requires double-quoted keys. This short example catches a syntax error without printing a traceback:
Save as demo_json_3.py:
import json
try:
json.loads('{name: "demo"}')
except json.JSONDecodeError:
print("Invalid JSON")Run:
python3 demo_json_3.pyOutput:
Invalid JSONParsing successfully does not check your application’s required keys or value types. Validate those before using data from another source, and limit the size of untrusted input.
Reference
Acknowledgements
This post was created with assistance from AI.