Python Validictory(JSON模式验证):如何OR多个模式?

时间:2013-05-31 08:18:36

标签: python json validation

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

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",
  ...
}

我一直在测试几种方法,但没有成功......任何想法? THX

1 个答案:

答案 0 :(得分: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)

我希望这会有所帮助。