【问题标题】:jsonschema validation with conditional format带条件格式的 jsonschema 验证
【发布时间】:2018-10-24 19:46:15
【问题描述】:

我有一个要添加“格式”关键字的架构,但仅限于某些情况。我有 jsconschema 草案 07 并且我正在尝试使用 if/else 语句,但是,我想我开始意识到使用 if/else 关键字时无法添加格式。

这是我的架构:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://json-schema.org/draft-07/schema#",
  "title": "Core schema meta-schema",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "theToggler": {
      "type": "string"
    },
    "mysession": {
      "$ref": "#/definitions/mysession"
    }
  },
  "definitions": {
    "mysession": {
      "type": "object",
      "properties": {
        "theID": {
          "type": "string",
          "example": "test@email.om",
          "description": "no format"
        }
      }
    }
  },
  "if": {
    "theToggler": "testme"
  },
  "then": {
    "definitions": {
      "mysession": {
        "type": "object",
        "properties": {
          "theID": {
            "type": "string",
            "format": "email"
          }
        }
      }
    }
  }
}

这是我的意见:

{
  "theToggler": "testme",
  "mysession": {
    "theID": "test"
  }
}

您会认为这会引发一个箭头(如果 'theToggler' = "testme" 那么 theID 应该有一个 @ 符号,因为我正在定义“电子邮件”格式。我做错了什么,还是不支持,或者你还有什么我可能遗漏的吗?

谢谢!

附:我正在https://www.jsonschemavalidator.net中测试它

【问题讨论】:

  • 这里的架构至少存在 3 个问题。没关系,阅读规范很难,我们随时为您提供帮助。我现在不能给你一个完整的答案,但我可以指出你的问题。首先,if 的值必须是 JSON Schema。 then 仅在 if 架构有效时使用。其次,作为 then 值的模式实际上并没有做任何事情,因为它自己的定义不会强加任何验证。 then 架构没有像您假设的那样添加到根架构,但它本身作为架构应用到数据实例。有意义吗?
  • 看看这些例子如何使用if/then/elsegithub.com/epoberezkin/ajv/blob/master/KEYWORDS.md#ifthenelse

标签: json validation jsonschema


【解决方案1】:

你有很多问题。

首先,您似乎使用了元模式作为示例。这很好,但您不能重用元模式的$id。您的架构需要有一个唯一的 $id 或根本没有。

ifthen 关键字必须是模式。如果实例对if 架构有效,那么then 架构也必须有效。

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "theToggler": { "type": "string" },
    "mysession": { "$ref": "#/definitions/mysession" }
  },
  "allOf": [
    {
      "if": { "$ref": "#/definitions/thetoggler-is-testme" },
      "then": { "$ref": "#/definitions/mysession-id-is-an-email" }
    }
  ],
  "definitions": {
    "mysession": {
      "type": "object",
      "properties": {
        "theID": {
          "type": "string",
          "example": "test@email.om",
          "description": "no format"
        }
      }
    },
    "thetoggler-is-testme": {
      "properties": {
        "theToggler": { "const": "testme" }
      }
    },
    "mysession-id-is-an-email": {
      "properties": {
        "mysession": {
          "properties": {
            "theID": { "format": "email" }
          }
        }
      }
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多