'JSON SCHEMA conditional: how can I require the key name in some of the list?
The JSON schema I want to implement can constrain the attributes under name into a list, as fellow code, I want the name should be input, and the name object the name of people should be some of ["TOM", "JACK","LILY","BRUCE"].
{
"NAME":{
"TOM": "male",
"JACK": "male"
}
} #This object meets the requirements
{
"NAME":{
"TOM": "male",
"LILY": "female"
"BRUCE": "male"
}
} #This object meets the requirements
{
"NAME":{
"JERRY": "male",
"LILY": "female"
"BRUCE": "male"
}
} #This object not meets the requirements beacuse JERRY not in the list.
{
"type": "object",
"required": ["NAME"],
"properties": {
"NAME": {
"type": "object",
"required": [],
"properties": {
"TOM": {
"type": "string"
},
"JACK": {
"type": "string"
},
"LILY": {
"type": "string"
},
"BRUCE": {
"type": "string"
}
}
}
}
}
Solution 1:[1]
You need to use the propertyNames keyword...
If the instance is an object, this keyword validates if every property name in the instance validates against the provided schema. Note the property name that the schema is testing will always be a string.
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6.5.8
{
"$schema": "http://json-schema.org/draft-07/schema",
"properties": {
"NAME":{
"propertyNames": {
"enum": ["TOM", "JACK","LILY","BRUCE"]
}
}
}
}
See it working here: https://jsonschema.dev/s/VQa7a
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Relequestual |
