【问题标题】:how to define alternative structure in json schema如何在 json 模式中定义替代结构
【发布时间】:2015-02-26 12:26:35
【问题描述】:

我的 JSON 文件看起来像这样:

{
    "api": "http://my.api.host",
    "modules": [
        "core", "module", "another"
    ]
}

或者这个:

{
    "api": "http://my.api.host",
    "modules": "*"
}

请注意,modules 属性的值可以是数组,也可以是* 字符串。如何在 JSON 模式中做到这一点?使用无价的http://jsonschema.net/ 我创建了以下仅验证数组的结构:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "http://jsonschema.net",
  "type": "object",
  "additionalProperties": true,
  "properties": {
    "api": {
      "id": "http://jsonschema.net/api",
      "type": "string",
      "minLength": 1
    },
    "modules": {
      "id": "http://jsonschema.net/modules",
      "type": "array",
      "minItems": 1,
      "uniqueItems": false,
      "additionalItems": true,
      "items": {
        "id": "http://jsonschema.net/modules/2",
        "type": "string",
        "minLength": 1
      }
    }
  },
  "required": [
    "api",
    "modules"
  ]
}

如何在 JSON 模式中进行替代?

【问题讨论】:

    标签: javascript json jsonschema


    【解决方案1】:

    我找到了答案,基于另一个(略有不同)SO question。解决方案是使用anyOf,它可以定义至少一个必须匹配的替代子模式。我的案例的一个示例解决方案是:

    {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "id": "http://jsonschema.net",
      "type": "object",
      "additionalProperties": true,
      "properties": {
        "api": {
          "id": "http://jsonschema.net/api",
          "type": "string",
          "minLength": 1
        },
        "modules": {
          "id": "http://jsonschema.net/modules",
          "anyOf": [{
            "type": "array",
            "minItems": 1,
            "uniqueItems": true,
            "items": {
              "id": "http://jsonschema.net/modules/2",
              "type": "string",
              "minLength": 1
            }
          }, {
            "type": "string",
            "minLength": 1
          }]
        }
      },
      "required": [
        "api",
        "modules"
      ]
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-14
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      • 2021-06-09
      相关资源
      最近更新 更多