I have a JSON Schema in which I wish to define all the objects of my projects. I want to be able to validate all my objects through this single JSON Schema (using the "jsonschema" python library). I don't want to create a schema file for each object in order to avoid repetitions.
Consider the following illustrative toy example (toy-schema.json
):
{
"$schema":"https://json-schema.org/draft/2020-12/schema",
"$id":"https://example.com/toy-example.json",
"title": "JSON Schema",
"description": "JSON Schema deifning objects a,b and c",
"type": "object",
"$defs":{
"a": {
"$id": "#a",
"type": "object",
"properties": {
"c_array": {
"type": "array",
"items": {
"$ref": "#/$defs/c"
}
}
},
"required": ["c_array"]
},
"b": {
"$id": "#b",
"type": "object",
"properties": {
"c": {"ref": "#/$defs/c"}
},
"required": ["c"]
},
"c": {
"$id": "#c",
"type": "number",
"minimum": 0
}
},
"allOf": [{"$ref": "#/$defs/a"}]
}
The following code works to validate an "a" object (thanks to the "allOf" instruction added at the bottom):
import jsonschema, json
with open("toy-schema.json", "r") as f: schema = json.load(f)
a = {"c_array": [1,2,3]}
jsonschema.validate(a, schema) ## is valid, correctly stays silent
a = {"c_array": [-1,2,3]}
jsonschema.validate(a, schema) ## is invalid (-1 < 0), correctly raises ValidationError
I want to also be able to validate object "b", ideally with a syntax looking like this:
import jsonschema, json
with open("toy-schema.json", "r") as f: schema = json.load(f)
b = {"c": 1}
jsonschema.validate(b, schema, "/$defs/#b") ## valid
b = {"c": -1}
jsonschema.validate(b, schema, "/$defs/#b") ## invalid
- Is it possible to do this ? I.e, point to a specific portion of the schema for validation (and thus retaining references to other objects' definitions within the same schema)
- Is this advisable or an anti-pattern ? In that case which JSON Schema structure would be more advisable for my problem ?
I believe something like this would be nice to avoid any schema definitions duplication.