Valid JSON is not necessarily a valid configuration. A retry count can be out of range, a key can be misspelled, and true can arrive where an integer was expected. Finding one error per run makes a simple setup frustrating.
This example parses a small local configuration and reports its field mistakes together, in a predictable order. It also rejects duplicate keys instead of silently taking the last value. Nothing connects to a server or changes a setting.
Run the example
Create validate_json_config.py in PythonIDE, paste the complete script below, and run it. Only the standard-library json module is needed. The configurations are synthetic strings inside the script, so there are no files to find or accounts to configure. The same file can run with desktop Python 3.
import json RULES = { "project": (str, lambda v: bool(v.strip()), "non-blank text"), "retries": (int, lambda v: 0 <= v <= 5, "integer 0..5"), "timeout": (int, lambda v: 1 <= v <= 60, "integer 1..60"), "verbose": (bool, lambda v: True, "true or false"), } def unique_keys(pairs): result = {} for key, value in pairs: if key in result: raise ValueError(f"duplicate key: {key}") result[key] = value return result def validate(source): try: config = json.loads(source, object_pairs_hook=unique_keys) except json.JSONDecodeError as error: return [f"JSON syntax: line {error.lineno}, column {error.colno}"] except ValueError as error: return [str(error)] if type(config) is not dict: return ["root: expected an object"] errors = [f"unknown key: {k}" for k in sorted(config.keys() - RULES.keys())] for key, (kind, check, hint) in RULES.items(): if key not in config: errors.append(f"{key}: missing") elif type(config[key]) is not kind or not check(config[key]): errors.append(f"{key}: expected {hint}") return errors good = '{"project":"demo","retries":2,"timeout":30,"verbose":false}' bad = '{"project":" ","retries":true,"timeout":0,"verbose":"no","retry":2}' assert validate(good) == [] expected = ["unknown key: retry", "project: expected non-blank text", "retries: expected integer 0..5", "timeout: expected integer 1..60", "verbose: expected true or false"] assert validate(bad) == expected assert validate("[]") == ["root: expected an object"] assert validate('{"project":"demo"}') == [ "retries: missing", "timeout: missing", "verbose: missing"] assert validate('{"retries":1,"retries":2}') == ["duplicate key: retries"] assert validate('{"project":}') == ["JSON syntax: line 1, column 12"] for value in (-1, 6, True, 2.0, "2"): config = json.loads(good) config["retries"] = value assert validate(json.dumps(config)) == ["retries: expected integer 0..5"] for label, source in (("VALID", good), ("INVALID", bad)): errors = validate(source) print(f"{label}: {len(errors)} error(s)") for index, error in enumerate(errors, 1): print(f" {index}. {error}") print("11 configuration checks passed.") Read the report
The actual run in PythonIDE on an English iPhone simulator produced:
VALID: 0 error(s) INVALID: 5 error(s) 1. unknown key: retry 2. project: expected non-blank text 3. retries: expected integer 0..5 4. timeout: expected integer 1..60 5. verbose: expected true or false 11 configuration checks passed. The rule dictionary is the small schema: a required key, its exact Python type, a value check, and a readable hint. Unknown keys come first in alphabetical order. Field errors then follow the rule dictionary's insertion order, keeping the report stable even if the input keys move around.
Notice type(value) is int rather than isinstance(value, int). In Python, booleans are subclasses of integers. A loose integer check would accept JSON true as a retry count. This example deliberately rejects booleans, floats such as 2.0, and numeric strings such as "2" for integer fields. It reports errors without silently converting values.
The object_pairs_hook receives key-value pairs before they become a dictionary. That lets unique_keys detect duplicates before one value overwrites another. The hook applies to every JSON object it parses. A malformed document, duplicate key, or non-object root stops validation at that stage. Once parsing succeeds with an object, field validation collects all its mistakes.
Test more than the happy path
Six assertions cover a valid configuration, the complete five-error report, an array root, missing fields, duplicate keys, and a syntax error with its line and column. Five more checks exercise invalid retry values: below the range, above the range, a boolean, a float, and a string.
The validator handles this fixed, flat schema. It is not a full JSON Schema implementation, and it does not provide defaults, normalize whitespace, validate nested application settings, or execute a job. If you later read a config file, handle file access separately and call this function on the resulting text before using the values.
Try one change
Allow up to ten retries by changing both the predicate and its hint. Replace 6 in the invalid-value tests with 11, then add success checks for 0 and 10. This keeps the rule, user-facing explanation, and boundary tests in agreement.
I build PythonIDE, a Python coding app for iPhone and iPad. AI assisted with drafting and translation.






