Valid JSON is not necessarily a valid application configuration. A file may parse into a list when your program expects an object, contain a misspelled setting, or use a Boolean where a timeout should be an integer. Validate the shape and meaning before starting work that depends on it.
Assume the program accepts two settings: mode is either preview or run, and retries is an integer from 0 through 5. Reject unknown keys for this small contract so misspellings do not disappear silently. Larger systems may need a formal schema library, but the distinction between syntax and semantics remains the same.
import json
def validate_config(text):
config = json.loads(text)
if not isinstance(config, dict):
raise ValueError("configuration must be an object")
if set(config) != {"mode", "retries"}:
raise ValueError("expected exactly mode and retries")
if config["mode"] not in ("preview", "run"):
raise ValueError("mode must be preview or run")
retries = config["retries"]
if type(retries) is not int or not 0 <= retries <= 5:
raise ValueError("retries must be an integer from 0 to 5")
return config
assert validate_config('{"mode":"preview","retries":2}')["retries"] == 2In Python, bool is a subclass of int. Using isinstance(value, int) alone would accept True as a retry count. The exact type check here matches the stated contract. In another application, accepting a numeric string might be reasonable, but that coercion should be intentional and documented.
Malformed JSON raises JSONDecodeError; the domain checks raise ValueError with an explanation. At the application boundary, display a concise message and exit before performing work. Do not include an entire configuration file in an error log if it may contain credentials. Keep secret values outside examples and source control.
If you later make retries optional, insert a documented default and run it through the same checks. Avoid a long sequence of get calls that silently invent settings. Decide whether a future schema version will allow additional fields and how older programs should react to them.
Add a required output_format key that accepts json or csv. Test malformed JSON, an array, missing keys, retries=true and retries=6. Explain which failure is a syntax error and which is a configuration error.
Explore the related Code Hacker course syllabus for structured learning. Then read Python CSV Validation: Build a Row-by-Row Error Report to connect this exercise to the next skill.
Python json module provides the underlying API or technical guidance. Check the documentation for the version you use; examples here are small learning exercises rather than complete production implementations.
Found an issue with this guide? Send a correction with the article URL and your example. About our learning material.
Subscribe to Code Hacker and get hands-on access to 40+ premium courses — Ethical Hacking, Kali Linux, Metasploit, Network Hacking, Bug Bounty & more!