PLAIN PYTHON · ZERO RUNTIME DEPS
Validate a JSON object
Parse JSON with the standard library, enforce an object root, then validate Python fields.
Parsing and validation are separate steps
Use json.loads() to parse the text, check for an object root, then validate its fields. Invalid JSON and a valid JSON object with incorrect fields fail at different boundaries.
import json
from zodify import validate
def read_user(text):
data = json.loads(text)
if type(data) is not dict:
raise ValueError("Expected a JSON object")
return validate({"name": str, "age": int}, data)
assert read_user('{"name":"Ada","age":36}')["age"] == 36
for invalid in ['[]', '{"name":"Ada","age":"36"}', '{"name":']:
try:
read_user(invalid)
except ValueError: # Includes JSONDecodeError.
pass
else:
raise AssertionError("Expected parsing or validation failure")
print("json-object-validation: passed")
Expected output: json-object-validation: passed
This is a Python object contract
The standard parser keeps the last duplicate object key and accepts non-finite numeric constants by default. This recipe does not promise duplicate-key rejection, strict JSON-number policy, or JSON Schema equivalence. Set input-size limits before parsing untrusted payloads.
The int schema rejects a parsed 1.0 because it is a Python float. For a JSON Schema contract, use a JSON Schema validator. A validate_json helper and export API are not in the documented release.