gpt4 book ai didi

Python Validictory(JSON 模式验证): How to OR multiple schemas?

转载 作者:行者123 更新时间:2023-11-28 22:55:28 24 4
gpt4 key购买 nike

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

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

我已经测试了几种方法但没有成功...有什么想法吗?谢谢

最佳答案

您可以在您的对象架构中使用属性 "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)

希望对您有所帮助。

关于Python Validictory(JSON 模式验证): How to OR multiple schemas?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16852846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com