Json Schema不同的输入格式

我正在AWS API Gateway中创建一些模型。我遇到一种问题,希望它可以接收2种输入格式:一种格式只是字典,另一种则是字典数组:

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

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

    {
        "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的方法,但是我不确定。

xugh1987 回答:Json Schema不同的输入格式

使用anyOf使您处在正确的轨道上。您应该做什么取决于它本身的对象(字典)与数组中的对象之间的相似性。它们在您的示例中看起来有所不同,因此我将以实物形式回答,然后说明如果它们实际上是相同的,则该如何简化。


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

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

将其包装在模式的根目录级别的anyOf

{  
  "$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#","definitions": {
    "myObject": {
      "type": "object","required": ["id"]
    }
  },"anyOf": [
    { "$ref": "#/definitions/myObject" },{
      "type": "array","items": { "$ref": "#/definitions/myObject" }
    }
  ]
}
本文链接:https://www.f2er.com/3157593.html

大家都在问