How can I check in the following json that at least one element in the array names
has a property nickName
with the value Ginny
?
{
"names": [
{
"firstName": "Hermione",
"lastName": "Granger"
}, {
"firstName": "Harry",
"lastName": "Potter"
}, {
"firstName": "Ron",
"lastName": "Weasley"
}, {
"firstName": "Ginevra",
"lastName": "Weasley",
"nickName": "Ginny"
}
]
}
Currently I'm using the draft-06 version (FAQ here).
This is my NOT WORKING schema:
{
"$schema": "http://json-schema.org/draft-06/schema#",
"title": "Complex Array",
"description": "Schema to validate the presence and value of an object within an array.",
"type": "object",
"properties": {
"names": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"nickName": {
"type": "string"
}
},
"anyOf": [
{"required": ["nickName"]}
]
}
}
}
}
The additionalProperties keyword is used to control the handling of extra stuff, that is, properties whose names are not listed in the properties keyword or match any of the regular expressions in the patternProperties keyword. By default any additional properties are allowed.
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.
Here oneOf is a keyword construct in the JSON Schema, which is used to provide an array of criteria where, if exactly one of them is valid, the whole block is valid. As per the exampe above, objects having ( "email" AND "password" ) OR ( "username" AND "password" ) attributes are considered valid.
A JSON object contains zero, one, or more key-value pairs, also called properties. The object is surrounded by curly braces {} . Every key-value pair is separated by a comma.
I managed to figure it out using draft-06
. On this version a new keyword contains
was added. According to this draft specification:
contains
The value of this keyword MUST be a valid JSON Schema. An array instance is valid against "contains" if at least one of its elements is valid against the given schema.
Working schema:
{
"$schema": "http://json-schema.org/draft-06/schema#",
"title": "Complex Array",
"type": "object",
"properties": {
"names": {
"type": "array",
"minItems": 1,
"contains": {
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"nickName": {
"type": "string",
"pattern": "^Ginny$"
}
},
"required": ["nickName"]
},
"items": {
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"nickName": {
"type": "string"
}
}
}
}
}
}
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