Skip to content

Instantly share code, notes, and snippets.

@MichaelBlume
Created October 20, 2012 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelBlume/3921530 to your computer and use it in GitHub Desktop.
Save MichaelBlume/3921530 to your computer and use it in GitHub Desktop.
Transformations on JSON schemas. Also strictness.
def rec_schema_transform(transform):
def recur(schema):
if not isinstance(schema, dict):
return
transform(schema)
for k, v in schema.items():
if k in ("properties", "patternProperties", "dependencies"):
for _, subschema in v.items():
recur(subschema)
elif k in ("additionalProperties", "additionalItems") and v:
recur(v)
elif k == "items":
if isinstance(v, list):
for subschema in v:
recur(subschema)
else:
recur(v)
return schema
return recur
@rec_schema_transform
def make_strict(schema):
if "properties" in schema and "additionalProperties" not in schema:
schema["additionalProperties"] = False
if "required" not in schema:
schema["required"] = True
@MichaelBlume
Copy link
Author

make_strict takes a JSON schema (as documented here: http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.8) and makes it default to strict -- makes all properties required and all non-specified properties forbidden. All valid JSON schema are still expressible, this just makes the strict ones shorter.

@MichaelBlume
Copy link
Author

Yes, this'll mutate the value passed in rather than just creating a new schema and returning it. Seemed like the idiomatic way to do it in Python.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment