A relatively new addition to JSON Schema (draft-07) adds the if, then and else keywords. I cannot work out how to use these new key words correctly. Here is my JSON Schema so far:
{
"type": "object",
"properties": {
"foo": {
"type": "string"
},
"bar": {
"type": "string"
}
},
"if": {
"properties": {
"foo": {
"enum": [
"bar"
]
}
}
},
"then": {
"required": [
"bar"
]
}
}
If the "foo" property equals "bar", Then the "bar" property is required. This works as expected.
However, if the "foo" property does not exist or input is empty then I don't want anything. how to acheive this?
empty input {}.
Found Errors:
Required properties are missing from object: bar.
Schema path: #/then/required
I use online validation tool:
https://www.jsonschemavalidator.net/
JSON Schema is a language for declaring the structure of valid JSON data. There are validators that can decide whether a specific JSON document is valid with respect to a schema.
react-jsonschema-form supports custom widgets for oneOf, anyOf, and allOf. A schema with oneOf is valid if exactly one of the subschemas is valid. A schema with anyOf is valid if at least one of the subschemas is valid. A schema with allOf is valid if all of the subschemas are valid.
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.
JSON Schema Validation: The JSON Schema Validation specification is the document that defines the valid ways to define validation constraints. This document also defines a set of keywords that can be used to specify validations for a JSON API.
The if
keyword means that, if the result of the value schema passes validation, apply the then
schema, otherwise apply the else
schema.
Your schema didn't work because you needed to require "foo"
in your if
schema, otherwise an empty JSON instance would pass validation of the if
schema, and therefore apply the then
schema, which requires "bar"
.
Second, you want "propertyNames":false
, which prevents having any keys in the schema, unlike if you were to set "else": false
which would make anything always fail validation.
{
"type": "object",
"properties": {
"foo": {
"type": "string"
},
"bar": {
"type": "string"
}
},
"if": {
"properties": {
"foo": {
"enum": [
"bar"
]
}
},
"required": [
"foo"
]
},
"then": {
"required": [
"bar"
]
},
"else": false
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With