Som*_*ath 5 validation json jsonschema json-schema-validator
看起来两者都适用于我的输入验证代码.那究竟是什么区别?
具有oneof的架构
[{
"id": "MyAction",
"oneOf": [{ "$ref": "A1" },
{ "$ref": "A2" }]
},
{
"id": "A1",
"properties": {
"class1": { "type": "string"},
"class2": { "type": "string"}
}
},
{
"id": "A2",
"properties": {
"class2": { "type": "string"},
"class3": { "type": "string"}
}
}
]
Run Code Online (Sandbox Code Playgroud)
架构与任何
[{
"id": "MyAction",
"anyOf": [{ "$ref": "A1" },
{ "$ref": "A2" }]
},
{
"id": "A1",
"properties": {
"class1": { "type": "string"},
"class2": { "type": "string"}
}
},
{
"id": "A2",
"properties": {
"class2": { "type": "string"},
"class3": { "type": "string"}
}
}
]
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 15
如果您查看JSON Schema文档,它会说:
5.5.4.任何
5.5.4.1.有效值
该关键字的值必须是一个数组.这个数组必须至少有一个元素.
数组的元素必须是对象.每个对象必须是有效的JSON模式.
5.5.4.2.成功验证的条件
如果实例针对此关键字的值定义的至少一个模式成功验证,则实例将针对此关键字成功验证.
5.5.5.oneOf
5.5.5.1.有效值
该关键字的值必须是一个数组.这个数组必须至少有一个元素.
数组的元素必须是对象.每个对象必须是有效的JSON模式.
5.5.5.2.成功验证的条件
如果实例针对此关键字的值定义的一个模式成功验证,则实例将针对此关键字成功验证.
请注意我在上面的重点.anyOf表示该项必须针对至少一个(但可能不止一个)模式进行验证.oneOf意味着它必须只针对其中一个模式进行验证.
我在探索中迟到了,但根据我的理解,此关键字的使用取决于对象/父对象本身的类型。例如,如果您尝试定义对象的单个属性或数组的元素的类型。以下面的例子为例:
{
"title": "Sample JSON Schema",
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"definitions": {
"propObjectType1" : {
"name": "string",
"age": "number"
},
"propObjectType2" : {
"name": "string",
"dob": {
"type": "string",
"pattern": "\\d\\d\/\\d\\d\/\\d\\d\\d\\d"
}
}
},
"properties": {
"prop1": {
"type": "string",
"maxLength": 64
},
"prop2": {
"anyOf": [
{
"$ref": "#/definitions/propObjectType1"
},
{
"$ref": "#/definitions/propObjectType2"
}
]
},
"prop3": {
"oneOf": [
{
"$ref": "#/definitions/propObjectType1"
},
{
"$ref": "#/definitions/propObjectType2"
}
]
},
"prop4Array": {
"type": "array",
"items": {
"oneOf": [
{
"$ref": "#/definitions/propObjectType1"
},
{
"$ref": "#/definitions/propObjectType2"
}
]
}
},
"prop5Array": {
"type": "array",
"items": {
"anyOf": [
{
"$ref": "#/definitions/propObjectType1"
},
{
"$ref": "#/definitions/propObjectType2"
}
]
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,在上面的定义中, prop2 和 prop3 是相同的(您可以互换使用anyOf或oneOf),您可以定义您觉得舒服的内容。但是,如果是数组:
anyOf项目类型时,元素可以是其中的任何类型,并且数组可以包含混合项目。意味着您可以拥有一项类型 1 的项目和另一项类型 2 的项目。oneOf项目类型时,元素可以是其中的任何类型,并且数组只能包含一种类型的项目。意味着所有项目必须属于同一类型(类型 1 或类型 2)。| 归档时间: |
|
| 查看次数: |
5363 次 |
| 最近记录: |