【发布时间】:2015-10-28 15:30:56
【问题描述】:
我想知道我是否可以定义一个 JSON 模式(草案 4),该模式至少需要一个对象的许多可能属性。我已经知道allOf、anyOf 和oneOf,但就是不知道如何以我想要的方式使用它们。
这里有一些示例 JSON 来说明:
// Test Data 1 - Should pass
{
"email": "hello@example.com",
"name": "John Doe"
}
// Test Data 2 - Should pass
{
"id": 1,
"name": "Jane Doe"
}
// Test Data 3 - Should pass
{
"id": 1,
"email": "hello@example.com",
"name": "John Smith"
}
// Test Data 4 - Should fail, invalid email
{
"id": 1,
"email": "thisIsNotAnEmail",
"name": "John Smith"
}
// Test Data 5 - Should fail, missing one of required properties
{
"name": "John Doe"
}
我想至少要求id 或email(也接受它们)并且仍然根据格式通过验证。如果我同时提供两者(测试 3),使用 oneOf 验证失败,anyOf 验证通过,即使其中一个无效(测试 4)
这是我的架构:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "https://example.com",
"properties": {
"name": {
"type": "string"
}
},
"anyOf": [
{
"properties": {
"email": {
"type": "string",
"format": "email"
}
}
},
{
"properties": {
"id": {
"type": "integer"
}
}
}
]
}
您能帮我如何正确验证我的用例吗?
【问题讨论】:
标签: json jsonschema