问题
My question for jsonschema is twofold:
Given
{
"foo": {"ar": {"a": "r"}},
"bar": ""
}
How do I check if the key "ar" exists inside of "foo"?
And only if "ar" exists inside of "foo", how do I make it so that "bar" must exists inside the given json?
I have tried looking other SO answers or jsonschema docs, but they only seem to check if the key has a specific value rather than if the key just exists regardless of its value. And the jsonschema for nested objects only seem to check for the deepest level of the nest rather than somewhere in the middle.
I have come up with this, but it doesn't work.
{
"definitions": {},
"$schema": "https://json-schema.org/draft-07/schema#",
"$id": "https://example.com/root.json",
"type": "object",
"properties": {
"foo": {
"type": "object"
},
"bar": {
"type": "string"
}
},
"required": [
"foo"
],
"if": {
"properties": {
"foo": {
"properties": {
"ar": {
"type": "object"
}
}
}
}
},
"then": {
"required": [
"bar"
]
}
}
回答1:
To test if the property is present, use the required
keyword.
{
"properties": {
"foo": {
"required": ["ar"]
}
},
"required": ["foo"]
}
This schema validates to true if /foo/ar
is present and false if it's not. Use this in place of your if
schema and your conditional should work as expected.
来源:https://stackoverflow.com/questions/56299562/json-schema-conditional-required-if-and-only-if-a-specific-key-exists-in-nested