Python 有没有一种方法可以使用JSON模式在字段之间强制执行值?
我最近开始使用,开始强制API有效负载。我在为遗留API定义模式时遇到了一些障碍,遗留API的设计逻辑相当混乱,导致客户端误用端点(以及糟糕的文档) 以下是迄今为止的模式:Python 有没有一种方法可以使用JSON模式在字段之间强制执行值?,python,json,jsonschema,Python,Json,Jsonschema,我最近开始使用,开始强制API有效负载。我在为遗留API定义模式时遇到了一些障碍,遗留API的设计逻辑相当混乱,导致客户端误用端点(以及糟糕的文档) 以下是迄今为止的模式: { "type": "array", "items": { "type": "object", "properties": { "type": { "type": "string" },
{
"type": "array",
"items": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"object_id": {
"type": "string"
},
"question_id": {
"type": "string",
"pattern": "^-1|\\d+$"
},
"question_set_id": {
"type": "string",
"pattern": "^-1|\\d+$"
},
"timestamp": {
"type": "string",
"format": "date-time"
},
"values": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"type",
"object_id",
"question_id",
"question_set_id",
"timestamp",
"values"
],
"additionalProperties": false
}
}
请注意,对于question\u id和question\u set\u id,它们都采用一个数字字符串,可以是-1或其他非负整数
我的问题:有没有办法强制执行,如果question\u id设置为-1,那么question\u set\u id也设置为-1,反之亦然
如果我能让解析器对其进行验证,而不必在应用程序逻辑中进行检查,那就太棒了
为了增加上下文,我一直在使用python的jsl模块来生成这个模式。您可以通过将以下内容添加到
项目
模式中来实现所需的行为。它断言模式必须至少符合列表中的一个模式。两者都是“-1”或都是正整数。(我假设您有充分的理由将整数表示为字符串。)
对于
模式
,请尝试“^-1 |[\\d]+$”
。组在这里没有意义,您也不想匹配-11
。哦,是的,谢谢@flaschbier。是的。。。整数作为字符串不是我的首选。谢谢你的建议。我试试看。
"anyOf": [
{
"properties": {
"question_id": { "enum": ["-1"] },
"question_set_id": { "enum": ["-1"] }
}
},
{
"properties": {
"question_id": {
"type": "string",
"pattern": "^\\d+$"
},
"question_set_id": {
"type": "string",
"pattern": "^\\d+$"
}
}
}