I need to validate a json object that always have 2 properties:
- type
- name
type can be "A", "B" or "C",
when type is "A", also the property "foo" is required and no additional properties are allowed.
OK:
{
"type": "A",
"name": "a",
"foo": "a",
}
Not OK:
{
"type": "A",
"name": "a",
"foo": "a",
"lol": "a"
}
when type is "B", the property "bar" is required and no additional properties are allowed.
when type is "C", the property "bar" is required and optionally also "zen" property can be present.
OK:
{
"type": "C",
"name": "a",
"bar": "a",
"zen": "a"
}
{
"type": "C",
"name": "a",
"bar": "a",
}
Not OK:
{
"type": "C",
"name": "a",
"bar": "a",
"lol": "a"
}
Unfortunately the outstanding answer to this question partially cover my case, however I did not managed to build a jsonschema that works for me.
edit:
Here is what I tried.
{
"$schema": "http://json-schema.org/draft-04/schema",
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["A", "B", "C"]
},
"name": {"type": "string"},
"foo": {"type": "string"},
"bar": {"type": "string"},
"zen": {"type": "string"},
},
"anyOf": [
{
"properties": {"type": {"enum": ["A"]}},
"required": ["foo"],
},
{
"properties": {"type": {"enum": ["B"]}},
"required": ["bar"],
},
{
"properties": {"type": {"enum": ["C"]}},
"required": ["bar"],
},
]
}
My problem is that setting the field "additionalProperties" to false inside the objects in "anyOf" does not give me the expected result.
for instance the following json pass the validation despite it has the additional property "lol"
{
"type": "A",
"name": "a",
"foo": "a",
"lol": "a"
}