对对象数组的要求

时间:2018-11-27 14:25:35

标签: json jsonschema

我已编写模式:

{
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "alarms": {
        "type": "integer"
      },
      "events": {
        "type": "integer"
      },
      "statistics": {
        "type": "integer"
      }
    }
  },
  "oneOf": [
    {
    "required":["alarms"],
     "required":["events"],
     "required":["statistics"]
    } 
  ]
}

,不幸的是,该模式允许:

[{alarms: 1, events: 1}, {events:1}, {statistics:3}]

我的目标是仅正确验证:

[{alarms: 1, {events:3}, {statistics:7}] 

我正在尝试,但是没有成功。

2 个答案:

答案 0 :(得分:1)

根据JSON模式的documentation和您的示例,您要做的是验证“ Items”对象。另外,您在“ oneOf”验证中有一个错误。您应该将3个对象添加到“ oneOf”数组中,并且只有一个具有3个相同参数的对象。

    {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "alarms": {
            "type": "integer"
          },
          "events": {
            "type": "integer"
          },
          "statistics": {
            "type": "integer"
          }
        },
        "oneOf": [
         {
           "required":["alarms"]
         },
         {
           "required":["events"]
         },
         {
           "required":["statistics"]
         }
        ]
      },
    }

答案 1 :(得分:1)

通过查看示例,您似乎要避免的是拥有具有多个属性的对象。如果是这样,我将按照以下方式进行操作:

{
    "type": "array",
    "items": {
        "type": "object",
        "patternProperties": {
            "^(alarms|events|statistics)$": {
                "type": "integer"
            }
        },
        "additionalProperties": false,
        "minProperties": 1,
        "maxProperties": 1
    }
}