Let's say we have the following JSON Schema:
{
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "enum": ["Adam", "Daniel", "Mike"] },
"desc": { "type": ["string", "null"] }
},
"required": [
"name"
]
}
}
Is it possible to validate that the field "name" has the same value for all objects in the array?
Examples:
[
{"name": "Adam"},
{"name": "Adam", "desc": "good"},
]
[
{"name": "Mike"},
{"name": "Mike", "desc": "good"},
]
[
{"name": "Adam"},
{"name": "Adam", "desc": "good"},
{"name": "Mike", "desc": "bad"},
]
If you have an explicit list of possible values, as you've shown (i.e. "enum": ["Adam", "Daniel", "Mike"]
), then it's possible, but a bit verbose. You'd use an anyOf
.
{
"type": "array",
"items": {
"type": "object",
"properties": {
"desc": { "type": ["string", "null"] }
},
"required": [
"name"
]
},
"anyOf": [
{
"items": {
"properties": {
"name": { "const": "Adam" }
}
}
},
{
"items": {
"properties": {
"name": { "const": "Daniel" }
}
}
},
{
"items": {
"properties": {
"name": { "const": "Mike" }
}
}
}
]
}
This will ensure that all of the items are one of these three values and they're all the same.
I'd also delete the name
property from the /items/properties
keywrod as it's not necessary since you're explicitly listing the possible values in the anyOf
.
(Verified with my online playground, https://json-everything.net/json-schema)
If you're looking to do this with open-ended data, no, JSON Schema doesn't support that.