{
"$id": "https://example.com/person.schema.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
},
"lastName": {
"type": "string",
"description": "The person's last name."
},
"age": {
"description": "Age in years which must be equal to or greater than zero.",
"type": "integer",
"minimum": 0
}
}
"required": ["firstName", "lastName", "age"]
}
(根据@gregdennis的回答编辑(
给定上述模式,有效的数据将是
{
"firstName": "John",
"lastName": "Doe",
"age": 21
}
但我想让它";可选";,就像在我想允许空对象
// should pass
{}
但不是半模式
// Shouldn't pass
{
"firstName": "John"
}
您所拥有的已经是可选的,所以空对象应该通过。为了使这些属性成为必需,您需要将它们放在required
关键字中。
"required": [ "first name", "last name", "age" ]
但是,仅添加此关键字就无法验证空对象。
要解决此问题,请将其封装在oneOf
请求中,并使用另一个仅接受空对象的模式。
{
"oneOf": [
{ "const": {} },
{
// your schema from above along with required
}
]
}