【问题标题】:Is there a way to create an enum in jsonschema based on a same level property?有没有办法基于同级属性在 jsonschema 中创建枚举?
【发布时间】:2021-06-26 15:40:02
【问题描述】:

说明

我有一个 JSON 对象,它有两个属性(除其他外),即 categorysubcategory,我有一个函数来获取类别列表和另一个函数来获取给定类别的子类别。

所以我的架构看起来像这样:

{
  "type": "array",
  "items": {
    "type": "obect",
    "properties": {
      "category": {
        "type": "string",
        "enum": getCategories()
      },
      "subcategory": {
        "type": "string",
        "enum": getSubcategories(category)
      }
  }
}

注意:一个子类别只属于一个主要类别

问题

类别列表很大,我想用json模式检查类别和子类别是否有效,所以不知道有没有办法这样做。

使用npm package for node js

示例:

假设我有类别 A 和 B 以及 [A1,A2][B1,B2] ,如果要验证的 json 具有类别 A 我想检查子类别是否在 [A1,A2] 而不是 [A1,A2,B1,B2]

我尝试过的

尝试了其他 post 的 if-else 语句,但正如我所提到的,列表很大,看起来根本不是一个好习惯

【问题讨论】:

  • 您是说您不想内联架构中的类别列表吗?您可以以编程方式生成架构以包含列表,但您不能将代码嵌入架构本身。 JSON 模式是数据。
  • @Ether 不,我不是那个意思,如果解释不准确,我很抱歉。我的意思是,如果这有意义的话,我希望每个 json 都被限制在 json 中明确的类别中的子类别列表中,编辑问题,以便更清楚

标签: node.js jsonschema


【解决方案1】:

目前,需要if/then 构造来根据类别指定子类别值:

{
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "category": {
        "type": "string",
        "enum": [ ... ]
      },
      "subcategory": {
        "type": "string",
      },
    },
    "allOf": [
      {
        "if": {
          "properties": {
            "category": { "const": "option1" },
          }
        },
        "then": {
          "properties": {
            "subcategory": {
              "enum": [ ... ]
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "category": { "const": "option2" },
          }
        },
        "then": {
          "properties": {
            "subcategory": {
              "enum": [ ... ]
            }
          }
        }
      },
      { ... }
    ] 
  }
}

但是,有人提议为下一个规范草案添加一个新关键字,这将大大缩短语法:https://github.com/json-schema-org/json-schema-spec/issues/1082

【讨论】:

    猜你喜欢
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 2016-07-24
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多