Created
October 20, 2012 00:59
-
-
Save MichaelBlume/3921530 to your computer and use it in GitHub Desktop.
Transformations on JSON schemas. Also strictness.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
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.