在JSON模式中定义另一个选项时,需要使用可选选项

时间:2015-05-08 12:50:42

标签: json jsonschema

我希望在certificate标志设置为true时定义privateKeysecure。这有可能实现吗?

{
    type: 'object',
    properties: {
        'secure': {
            title: 'Serve files over HTTPS',
            description: 'Flag telling whether to serve contents over HTTPS and WSS',

            type: 'boolean',
            default: false
        },

        'certificate': {
            title: 'Certificate file',
            description: 'Location of the certificate file',

            type: 'string'
        },

        'privateKey': {
            title: 'Private key file',
            description: 'Location of the private key file',

            type: 'string'
        }
}

3 个答案:

答案 0 :(得分:1)

您可以使用'dependencies'关键字。

{
  dependencies: {
    secure: ['certificate', 'privateKey']
  }
}

您甚至可以指定在存在安全时数据应该匹配的架构:

{
  dependencies: {
    secure: {
      properties: {
        certificate: {
          type: 'string'
        }
        privateKey: {
          type: 'string'
        }
      },
      required: ['certificate', 'privateKey']
    }
  }
}

答案 1 :(得分:0)

您是否要求依赖于架构内容?我的意思是“模式允许的内容取决于目标(json)内容中的内容”?

你做不到。

答案 2 :(得分:0)

有一种方法,但它不漂亮。您需要使用anyOf关键字来定义在secure true时您希望如何进行验证,以及secure false时您希望如何进行验证

{
  "type": "object",
  "properties": {
    "secure": {
      "title": "Serve files over HTTPS",
      "description": "Flag telling whether to serve contents over HTTPS and WSS",
      "type": "boolean"
    }
  },
  "anyOf": [
    {
      "type": "object",
      "properties": {
        "secure": {
          "enum": [true]
        },
        "certificate": {
          "title": "Certificate file",
          "description": "Location of the certificate file",
          "type": "string"
        },
        "privateKey": {
          "title": "Private key file",
          "description": "Location of the private key file",
          "type": "string"
        }
      },
      "required": ["certificate", "privateKey"]
    },
    {
      "type": "object",
      "properties": {
        "secure": {
          "enum": [false]
        }
      }
    }
  ]
}