【问题标题】:How can I validate the string value of a key using JSON Schema?如何使用 JSON Schema 验证键的字符串值?
【发布时间】:2018-02-01 11:57:30
【问题描述】:

我发现很难理解如何使用不同的验证集来验证不同类型的响应。我只是放了一个示例代码,然后尝试解释它可能有意义。

示例数据集:

responses: [
   { type: 'user', age: 5 }
   { type: 'admi', auth: {...} }
]

json 架构示例:

{
    "definitions": {
        "user": {
            "type": "object",
            "properties": {
                "type": { "type": "string" },
                "age": { "type": "number" }
            }
            "required": ["age"]
        },
        "admin": {
            "type": "object",
            "properties": {
                "type": { "type": "string" },
                "auth": { "type": "object" }
            }
            "required": ["auth"]
        }
    },
  "responses": {
    "type": "array",
    "anyOf": [
      { "$ref": "#/definitions/user" }
      { "$ref": "#/definitions/admi" }
    ]
  }
}

如何根据类型验证这些(不是string, number,而是'user', 'admi')?

【问题讨论】:

  • 这里的语言有点混乱。对象的类型是您已定义的,并且您使用anyOf 走在正确的轨道上。我会尽快给出答案。

标签: json jsonschema json-schema-validator


【解决方案1】:

您将寻找适用于您的实例中的字符串或任何类型的验证关键字。在最新版本的 JSON Schema 中,您可以找到const

您可以为您的用户定义添加一个 const 关键字,如下所示...

...
    "user": {
        "type": "object",
        "properties": {
            "type": { "type": "string", "const": "user" },
            "age": { "type": "number" }
        }
        "required": ["age"]
    },
...

如果 const 对您不可用,因为您需要使用旧版本的 JSON Schema,您可以使用 enum,它实际上是 sam,但您可以将字符串“user”封装在数组中作为enum 关键字的值。

【讨论】:

  • 不客气。我是 JSON Schema 团队的一员。如果您想提出 SO 范围之外的问题,请随时加入 Slack 频道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
  • 2014-04-29
  • 2021-04-18
  • 2013-08-06
  • 2019-04-26
相关资源
最近更新 更多