gpt4 book ai didi

python - 如果可选属性无效,JSON 架构会抛出验证错误

转载 作者:行者123 更新时间:2023-12-01 00:19:40 24 4
gpt4 key购买 nike

我有一个如下所示的 json 模式,它具有三个可选属性:高度、重量和体积。但我想在这里进行以下额外检查:

  1. 如果传递了除高度、重量和体积之外的任何其他属性,那么它应该抛出错误

不确定如何实现这一点,因为这些是可选属性。

  {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"options": {
"type": "object",
"properties": {
"height": {
"type": "number"
},
"weight": {
"type": "number"
},
"volume": {
"type": "number"
}
}
}
}
}

最佳答案

您要查找的是additionalProperties 键。来自 JsonSchema docs

The additionalProperties keyword is used to control the handling of extra stuff, that is, properties whose names are not listed in the properties keyword. By default any additional properties are allowed.

所以,你会变成:

 {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"options": {
"type": "object",
"properties": {
"height": {
"type": "number"
},
"weight": {
"type": "number"
},
"volume": {
"type": "number"
}
},
"additionalProperties": false
}
}
}

据我了解,从 draft 00 开始就支持此功能,因此 draft 4 应该没问题,但请您注意,第 8 版已经在这里。

关于python - 如果可选属性无效,JSON 架构会抛出验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59045428/

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