对于只能在数组内的对象上设置一次的属性的Json模式验证

时间:2018-02-21 13:56:15

标签: json jsonschema

是否可以验证下面的json数据,以便" info"只有在" name"是" a"否则它必须为空或为空?

[
  {
    "name": "a",
    "info": "this is mandatory"
  },
  {
    "name": "b",
    "info": "validation must fail"
  }
]

JSONSchema

{
 "title": "Array of things",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "name": {
        "type": "string",
        "enum": [
          "a",
          "b"
        ]
      },
      "info": {
        "type": "string"
      }
    }
  }
}

online editor

中的json

1 个答案:

答案 0 :(得分:2)

试试这个:

{
 "title": "Array of things",
  "type": "array",
  "items": {
   "type": "object",
   "properties":  {
      "name": {
         "type": "string",
        "enum": ["a", "b"]
      },
      "info" : {
         "type": ["string", "null"]         
      }
   },
   "required": ["name"],

   "oneOf": [
      {
         "properties": {
             "name": {"enum": ["a"] }
         },
         "required": ["info"]
      },
     {
         "properties": {
             "name": {"enum": ["b"] },
"info": {"enum": [null]}
         }         
      }
   ]
}
}