2

我有多个模式,每个模式都用于数据子类型:

type_one = {
  "type": "object",
  "properties": {
    "one": "string"
  }
}

type_two = {
  "type": "object",
  "properties": {
    "one": "string",
    "two": "string"
  }
}

我想要检查传入的数据是“type_one”还是“type_two”或抛出错误。像这样的东西:

general_type = {
  "type": [type_one, type_two]
}

我的传入数据是这样的:

{
  "one": "blablabla",
  "two": "blebleble",
  ...
}

我一直在测试几种方法,但没有成功......有什么想法吗?谢谢

4

1 回答 1

4

您可以"additionalProperties": False在对象架构中使用该属性来只允许一组精确的键。

首先,让我们拥有有效的模式结构:

type_one = {
    "type": "object",
    "additionalProperties": False,
    "properties": {
        "one": {"type": "string"}
    }
}

type_two = {
    "type": "object",
    "additionalProperties": False,
    "properties": {
        "one": {"type": "string"},
        "two": {"type": "string"}
    }
}

general_type = {
    "type": [type_one, type_two]
}

注意:您问题的架构是"one": "string",应该是"one": {"type": "string"}

这是我们的输入数据:

data_one = {
    "one": "blablabla"
}

data_two = {
    "one": "blablabla",
    "two": "blablabla"
}

这是验证:

import validictory

# additional property 'two' not defined by 'properties' are not allowed
validictory.validate(data_two, type_one)

# Required field 'two' is missing
validictory.validate(data_one, type_two)

# All valid
validictory.validate(data_one, type_one)
validictory.validate(data_two, type_two)

validictory.validate(data_one, general_type)
validictory.validate(data_two, general_type)

我希望这有帮助。

于 2013-06-01T18:41:42.053 回答