如何在 JSON 模式验证器中表示联合类型?

6 jsonschema json-schema-validator

我是 JSON 架构验证的新手,正在为配置构建自定义架构。我正在构建的架构基于 Typescript 类型。我了解如何验证简单的数据类型,如数组、对象、数字、字符串等。

但是有没有办法指定这样的类型:

type Conf = {
  idle_session_timeout?: number | "none";
  item:
    | {
        kind: "attribute";
        name: string;
      }
    | {
        kind: "relation";
        name: string;
      }
    | {
        kind: "group";
        name: string;
        label?: string | undefined;
        entries: PresentationItem[];
      };
  order_by:
    | string
    | {
        attribute: string;
        direction?: "asc" | "desc" | undefined;
      };
};
Run Code Online (Sandbox Code Playgroud)

我从http://json-schema.org/draft-07/schema注意到它支持 if then else 语句来根据值切换验证模式,但我不知道如何实现它们。

aww*_*ght 6

您需要注意一些关键字,并且可能会参考以下规范:

首先,“type”允许在数组中指定多个值。有了这个,您可以指定例如["string", "number"]表示“字符串或数字”。许多关键字仅在实例属于某种 JSON 类型时适用。通常,如果所有剩余关键字仅适用于各自的类型,则可以将一种“类型”的模式与另一种具有不同“类型”的模式组合起来。

例如,您可以有两个模式,例如:

{
  "type": "string",
  "minLength": 1
}
{
  "type": "number",
  "minimum": 0
}
Run Code Online (Sandbox Code Playgroud)

并且因为“minimum”仅适用于数字,而“minLength”仅适用于字符串,因此您可以简单地将模式组合在一起,并且它将具有相同的效果:

{
  "type": ["string", "number"],
  "minLength": 1
  "minimum": 0
}
Run Code Online (Sandbox Code Playgroud)

但是,对于相同“类型”的两个模式,这样做将执行交集而不是并集。这是因为向 JSON 模式添加关键字会添加约束,而向“类型”列表添加值会删除约束(更多值变得有效)。

因此,如果您要对相同“类型”的两个模式执行联合,或者如果您要将模式与在所有类型(特别是“枚举”或“const”)上验证的关键字组合,则需要将它们与“ anyOf”关键字,它对多个模式的数组执行联合。(您也可以考虑“oneOf”。)


我认为你最终会得到这样的模式:

{
"type": "object",
"properties": {
  "idle_session_timeout": {
    "type": ["number","string"],
    "anyOf": [ {"type":"number"}, {"const":"none"} ]
  },
  "item": {
    "type": "object",
    "required": ["kind", "name"],
    "properties": {
      "kind": { "type": "string" },
      "name": { "type": "string" },
    },
    "anyOf": [
      {
        "properties": {
          "kind": { "const": "attribute" },
        }
      },
      {
        "properties": {
          "kind": { "const": "relation" },
        }
      },
      {
        "required": ["entries"],
        "properties": {
          "kind": { "const": "group" },
          "label": { "type": "string" },
          "entries": { "type":"array", "items": {"$ref":"PresentationItem"} },
        }
      }
    ]
  },
  "order_by": {
    "type": ["string", "object"],
    "required": ["attribute"],
    "properties": {
      "attribute": { "type": "string" },
      "direction": { "enum": ["asc", "desc"] },
    }
  }
}

Run Code Online (Sandbox Code Playgroud)

请注意我如何将“anyOf”中的常见关键字分解为可能的最高级别。这是一种风格选择。它会产生稍微干净的错误,但它可能与您无关,具体取决于您计划如何扩展架构。