Reputation: 5272
I have an object that has dynamic key names and I want to describe the value schema that the keys can have, ie:
{
"properties": {
"usersById": {
"additionalProperties": {
"properties": {
"email": {
"type": "boolean"
},
"phone": {
"type": "boolean"
},
"address": {
"type": "boolean"
}
},
"type": "object"
},
"type": "object"
}
},
...
}
This doesn't appear to be doing anything in my validation step (using AJV JS pkg). I want to restrict to only this model schema:
{
usersById: {
'1234abcd': {
email: true,
phone: false,
address: false,
},
},
}
Upvotes: 2
Views: 1590
Reputation: 12315
You can use patternProperties
which is like properties
but you use a regex.
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6.5.5
An example...
Schema:
{
"type": "object",
"patternProperties": {
"^S_": { "type": "string" },
"^I_": { "type": "integer" }
},
"additionalProperties": false
}
Valid instance:
{ "I_0": 42 }
Invalid instance:
{ "S_0": 42 }
Example lifted from https://json-schema.org/understanding-json-schema/reference/object.html#pattern-properties
As a note, it's good to remember that these regexes are not implicitly anchored, so you'll need to anchor them should you require anchored regexes.
Upvotes: 2