【问题标题】:JSON schema enum vs pattern for single valueJSON模式枚举与单值模式
【发布时间】:2016-03-09 05:09:27
【问题描述】:

我有一个示例 json:

{
    "type": "persons",
    "id": 2,
    "attributes": {
        "first": "something",
        "second": "something else"
    }
}

我必须为它创建一个架构(使用JSON API specsJSON schema docs):

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "properties": {
        "type": {
            "type": "string",
            "pattern": "^persons$"
        },
        "id": {
            "type": "integer"
        },
        "attributes": {
            "type": "object",
            "properties": {...}
        }
    },
    "required": ["type", "id", "attributes"]
}

问题是:如果“type”唯一可接受的值是“persons”,我应该在模式模式中使用(如上)还是像枚举一样

"enum": ["persons"]

我无法从文档中得到任何明确的答案,尽管在规范中的示例中枚举用于单个值。那么你有什么看法呢?

【问题讨论】:

    标签: json enums jsonschema json-api


    【解决方案1】:

    最终,这并不重要。两者都会起作用,而且都是合理的。也就是说,我见过的最常见的方法是使用enum。两者都不是完美的可读性,但我认为enum 更好有两个原因。

    1. 使用pattern需要两行来表达。使用enum 只需要一个,因为数组中的值隐含了type。两行比一行更难读,所以如果那一行足够表达,我说坚持用一行。

    2. 并不是每个人都喜欢阅读正则表达式。出于这个原因,enum 可能更易于访问。

    【讨论】:

      【解决方案2】:

      从草案 6 开始,此用例有一个名为 const 的新关键字。

      "type": {
              "type": "string",
              "const": "persons"
      },
      

      http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.1.3

      【讨论】:

      • 我认为你在使用const时不需要type
      猜你喜欢
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 2015-10-15
      • 2014-04-10
      • 1970-01-01
      • 2017-07-03
      相关资源
      最近更新 更多