有没有办法使用 JSON 模式来强制字段之间的值?
Is there a way to use JSON schemas to enforce values between fields?
我最近开始使用 JSON schemas 来强制执行 API 有效载荷。我在为遗留 API 定义架构时遇到了一些障碍,该架构具有一些非常笨拙的设计逻辑,导致(以及糟糕的文档)客户滥用端点。
目前的架构如下:
{
"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_id 和 question_set_id,它们都采用数字字符串,可以是-1 或其他一些非负整数。
我的问题:如果 question_id 设置为 -1,是否有办法强制执行 question_set_id 也设置为 -1,反之亦然。
如果我可以让解析器对其进行验证而不是必须在应用程序逻辑中进行检查,那就太棒了。
只是为了额外的上下文,我一直在使用 python 的 jsl 模块来生成这个模式。
您可以通过将以下内容添加到您的 items
架构来实现所需的行为。它断言模式必须至少符合列表中的模式之一。要么都是“-1”,要么都是正整数。 (我假设您有充分的理由将整数表示为字符串。)
"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+$"
}
}
}
我最近开始使用 JSON schemas 来强制执行 API 有效载荷。我在为遗留 API 定义架构时遇到了一些障碍,该架构具有一些非常笨拙的设计逻辑,导致(以及糟糕的文档)客户滥用端点。
目前的架构如下:
{
"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_id 和 question_set_id,它们都采用数字字符串,可以是-1 或其他一些非负整数。
我的问题:如果 question_id 设置为 -1,是否有办法强制执行 question_set_id 也设置为 -1,反之亦然。
如果我可以让解析器对其进行验证而不是必须在应用程序逻辑中进行检查,那就太棒了。
只是为了额外的上下文,我一直在使用 python 的 jsl 模块来生成这个模式。
您可以通过将以下内容添加到您的 items
架构来实现所需的行为。它断言模式必须至少符合列表中的模式之一。要么都是“-1”,要么都是正整数。 (我假设您有充分的理由将整数表示为字符串。)
"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+$"
}
}
}