0

我正在尝试使用 jsonschema lib 验证 JSON 模式。

场景:我需要确保属性中的特定值是否在父对象中发送,子(子模式)也应该在同一属性中获得相同的值。

JSON:->

{
"type": "object",
  "properties": {
"action": {
  "enum": [
    "get",
    "post"
  ]
},
"order": {
  "properties": {
    "id": "string",
    "action": {
      "enum": [
        "get",
        "post"
      ]
    }
  }
}},"dependentSchemas": {
"if": {
  "action": {
    "const": "get"
  }
},
"then": {
  "properties": {
    "order": {
      "properties": {
        "action": {
          "const": "get"
        }
      }
    }
  }
}
}
}

示例测试用例: 正面:

{
"action": "get",
"order": {
   "id" : "1"
   "action": "get"
      }
}

消极的:

{
"action": "get",
"order": {
   "id" : "2"
   "action": "post"
      }
}

我正在使用dependentSchemas 来验证子模式:-点击这里

4

1 回答 1

0

dependentSchemas不适用于这种情况。dependentSchemas分支基于属性的存在,而不是它的价值。您需要使用if/then对属性的值进行分支。

"allOf": [
  {
    "if": {
      "type": "object",
      "properties": {
        "action": { "const": "get" }
      },
      "required": ["action"]
    },
    "then": {
      "properties": {
        "order": {
          "action": { "const": "get" }
        }
      }
    }
  },
  ... Another if/then just like the first but with "post" ...
]

注意:typerequired关键字在if架构中是必需的,以便在极端情况下获得良好的错误消息。

于 2021-09-22T18:49:06.297 回答