仅当存在1个项目时,对多个项目的JSON模式条件验证才有效

rn0zuynd  于 2023-03-04  发布在  其他
关注(0)|答案(1)|浏览(89)

我有以下JSON:

{
  "inputs": [
    {
      "term": {
        "units": "liters",
        "termType": "material"
      }
    },
    {
      "term": {
        "units": "kilogram",
        "termType": "crop"
      }
    }
  ]
}

我想验证:

  • 如果inputs中任何元素具有termType=material
  • 那么units应该是kilogram

所以我把验证写成这样:

{
  "allOf": [
    {
      "if": {
        "required": [
          "inputs"
        ],
        "properties": {
          "inputs": {
            "items": {
              "properties": {
                "term": {
                  "properties": {
                    "termType": {
                      "const": "material"
                    }
                  }
                }
              }
            }
          }
        }
      },
      "then": {
        "properties": {
          "inputs": {
            "items": {
              "properties": {
                "term": {
                  "properties": {
                    "units": {
                      "const": "kilogram"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  ]
}

我正在使用ajv版本6来验证(启用了draft 07),并且它仅在inputs数组中只有一个元素时有效,因此如果我在

{
  "inputs": [
    {
      "term": {
        "units": "liters",
        "termType": "material"
      }
    }
  ]
}

它会给出一个错误,但是不使用数组中有两个元素的顶部的样本。为什么?

rlcwz9us

rlcwz9us1#

一般来说,在JSON Schema中,像这样的约束是这样定义的:

{
  "type": "object",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "description": "JSON schema generated with JSONBuddy https://www.json-buddy.com",
  "properties": {
    "inputs": {
      "type": "array",
      "items": { "$ref": "#/definitions/inputsItem" }
    }
  },
  "definitions": {
    "inputsItem": {
      "type": "object",
      "properties": {
        "term": {
          "type": "object",
          "properties": {
            "termType": { "type": "string" },
            "units": { "type": "string" }
          },
          "required": [ "units" ]
        }
      },
      "if": {
        "properties": {
          "term": {
            "properties": {
              "termType": { "const": "material" }
            }
          }
        }
      },
      "then": {
        "properties": {
          "term": {
            "properties": {
              "units": { "const": "kilogram" }
            }
          }
        }
      }
    }
  }
}

相关问题