Json Schema不同的输入格式



我正在AWS API网关中创建一些模型。我有一个问题,我希望它能接收2种输入格式:其中一种格式只是一个字典,另一种是字典数组:

{
"id":"",
"name":""
}

[
{
"id":"",
"Family":""
},
{
"id":"",
"Family":""
},
...
{
"id":"",
"Family":""
}
]

到目前为止,我已经创建了只接受字典方式的模型:

{  
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Update",
"type": "object",
"properties": {
"id": { "type": "string"},
"name": { "type": "string"}
},
"required": ["id"]
}

你能给我一些创建字典数组的技巧吗。我做了一些研究,什么也没发现,但我遵循关键字oneOf和anyOf的方式,但我不确定。

您使用anyOf是正确的。应该做什么取决于对象(字典(本身和数组中的对象之间的相似性。在你的例子中,它们看起来不同,所以我会用实物回答,然后展示如何在它们实际上相同的情况下简化它们。


要使用anyOf,您需要捕获定义字典的关键字

{
"type": "object",
"properties": {
"id": { "type": "string"},
"name": { "type": "string"}
},
"required": ["id"]
}

并在模式的根级别将其封装在CCD_ 3中

{  
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Update",
"anyOf": [
{
"type": "object",
"properties": {
"id": { "type": "string"},
"name": { "type": "string"}
},
"required": ["id"]
}
]
}

要为同类对象的数组编写模式,需要items关键字。

{
"type": "array",
"items": {
"type": "object",
"properties": {
"id": { "type": "string"},
"Family": { "type": "string"}
},
"required": ["id"]
}
}

将其作为anyOf数组中的第二个元素添加进来,您就获得了金牌。


如果您唯一的对象可以与数组元素对象具有相同的模式,那么您可以将该模式作为定义编写一次,并在两个位置引用它。

{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Update",
"definitions": {
"myObject": {
"type": "object",
"properties": {
"id": { "type": "string"},
"name": { "type": "string"}
},
"required": ["id"]
}
},
"anyOf": [
{ "$ref": "#/definitions/myObject" },
{
"type": "array",
"items": { "$ref": "#/definitions/myObject" }
}
]
}

最新更新