JSON模式使用条件验证oneOf

时间:2017-08-02 09:35:52

标签: javascript json jsonschema json-schema-validator ajv

如何为下一个对象设置json schema validator? 它们都包含字段account_id,但options依赖于type

如果twitter列有tokens,则其中每个都有四个字段。 如果typeinstagram,则每个令牌只有一个字段 tokens。 对于facebook type字段options必须为空。

{
  "type": "twitter",
  "account_id": "xyz",
  "options": {
    "tokens": [{
      "access_token": "long string",
      "access_token_secret": "long string",
      "consumer_key": "long string",
      "consumer_secret": "long string"
    }]
  }
}

{
  "type": "instagram",
  "account_id": "xyz",
  "options": {
    "tokens": [{
      "access_token": "long string"
    }]
  }
}

{
  "type": "facebook",
  "account_id": "xyz",
  "options": {}
}

是否可以制作满足这些要求的json架构?即使是最简单的架构,每个type的定义都包含在oneOf个关键字中也不起作用。

{
  "type": "object",
  "additionalProperties": false,
  "oneOf": [{
      "properties": {
        "account_id": {
          "type": "string",
        },
        "type": {
          "const": "facebook"
        },
        "options": {
          "type": "object",
          "additionalProperties": false
        }
      },
      "required": [
        "account_id",
        "type",
        "options"
      ]
    },
    {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "account_id": {
          "type": "string",
        },
        "type": {
          "const": "twitter"
        },
        "options": {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
              "access_token": {
                "type": "string"
              },
              "access_token_secret": {
                "type": "string"
              },
              "consumer_key": {
                "type": "string"
              },
              "consumer_secret": {
                "type": "string"
              }
            },
            "required": [
              "access_token",
              "access_token_secret",
              "consumer_key",
              "consumer_secret"
            ]
          }
        }
      },
      "required": [
        "account_id",
        "type",
        "options"
      ]
    },
    {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "account_id": {
          "type": "string",
        },
        "type": {
          "const": "instagram"
        },
        "options": {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
              "access_token": {
                "type": "string"
              }
            },
            "required": [
              "access_token"
            ]
          }
        }
      },
      "required": [
        "account_id",
        "type",
        "options"
      ]
    }
  ]
}

感谢您的任何建议!

0 个答案:

没有答案