首页 > 解决方案 > 有没有办法基于同级属性在 jsonschema 中创建枚举?

问题描述

描述

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

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

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

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

问题

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

为节点 js使用npm 包

例子:

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

我试过的

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

标签: node.jsjsonschema

解决方案


目前,需要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


推荐阅读