Json 架构 - 不需要则不起作用

标签 json jsonschema

我有一个情况,我正在有条件地验证所需的属性。

“不需要”未按预期工作。

如果“profile”为 profile1,则“rate”、“trick”和“tag”字段是必需的,并且“code”、“name”和“type”不应​​出现。

如果“profile”为 profile2,则需要“code”,不需要“rate”、“tag”和“trick”。

如果“profile”是 profile3,则不需要“rate”、“tag”、“trick”、“code”、“name”和“type”。

我正在使用架构草稿版本 4

架构

{
  "type": "object",
  "properties": {
    "id": { "type": "integer" },
    "url": { "type": "string" },
    "profile": { "type": "string" },
    "rate": { "type": "string" },
    "trick": { "type": "boolean" },
    "tag": { "type": "string" },
    "type": { "type": "string" },
    "name": { "type": "string" },
    "code": { "type": "string" }
  },
  "additionalProperties": false,
  "required": [ "url", "profile" ],
  "oneOf": [
    {
      "properties": { "profile": { "enum": [ "profile1" ] } },
      "not": { "required": ["type", "name", "code"] }
    },
    {
      "properties": { "profile": { "enum": [ "profile2" ] } },
      "allOf": [
        { "required": [ "code" ] },
        { "not": { "required": ["rate", "tag", "trick"] } }
      ]
    },
    {
      "properties": { "profile": { "enum": ["profile3"] } },
      "not": { "required": ["rate", "trick", "tag", "type", "name", "code"] }
    }
  ]
}

有效输入

{
  "id": 1,
  "url": "url",
  "profile": "profile2",
  "type": "",
  "name": "",
  "code": ""
}
{
  "id": 1,
  "url": "url",
  "profile": "profile3"
}
{
  "id": 1,
  "url": "url",
  "profile": "profile1",
  "rate": "",
  "trick": false,
  "tag": ""
}

无效输入

{
  "url": "url",
  "profile": "profile3",
  "code": ""
}

最佳答案

我可以看到您是如何得出这种方法的,并且您可以使其发挥作用,但这不是最好的方法。

not 关键字反转值子模式的断言结果。

如果您采用 anyOf[2].not 架构...

{ "required": ["rate", "trick", "tag", "type", "name", "code"] }

这意味着,我相信您知道,所有这些属性都是必需的。

not 然后反转应用该子模式的结果。

因为在您希望验证失败的对象示例中,它只有该数组中的code,因此它不满足required约束。 p>

你可以让它 not > anyOf > [required > rates, required > trap... 等拥有许多子模式,但这会有点难看。

相反,您可以使用替代方法,并指定允许的内容...

您的 anyOf 将如下所示(演示: https://jsonschema.dev/s/zG9GF ):

"anyOf": [
    false,
    false,
    {
      "properties": {
        "profile": {
          "const": "profile3",
          "id": true
        }
      },
      "additionalProperties": false
    }
  ]

您可能会发现使用 Draft-07 中的 if/then/else 关键字更为惯用,然后您可以使用 allOf 并设置 else<如果您不想为 profile 使用顶级枚举,请将/code> 值设置为 false

关于Json 架构 - 不需要则不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60450958/

相关文章:

java - 为什么字符串中有逗号时 JSON 无效?

java - 缩短将一个 json 对象映射到另一个 json 对象的处理时间

使用 Apache Kafka Streaming 解析 JSON 数据

Json 模式允许覆盖数组中对象中的字段

php - laravel 4.1 用数据库中的数据填充表格

javascript - 将Json以特定格式传递给javascript以渲染图表

json - 使用对象键作为 JSON 架构中的类型

python - JSON 架构 : validate a number-or-null value

javascript - 在 node.js/express.js 中从多个异步源构建对象

json - 在 ajv-cli 中使用 $ref 中的 URI