使用其他必填字段扩展$ ref

Emi*_*äck 2 jsonschema

给定一个location类似这样的模式的一部分:

{
  type: 'object',
  required: [ 'country' ],
  additionalProperties: false,
  properties: {
    country: {
      enum: [ 'DE', 'CH', 'AT' ],
    },
    postalCode: { type: 'string' },
  },
};
Run Code Online (Sandbox Code Playgroud)

在我们的大多数用例中,只有国家/地区代码才能使位置有效.但是我们有几次需要邮政编码.

例如,在我们的案例中,公司总是需要postalCode.我们以前的location架构当然没有强制执行.其他模式需要不强制存在邮政编码的位置对象.这是我们公司的架构:

{
  type: 'object',
  required: [ 'name', 'location' ],
  additionalProperties: false,
  properties: {
    location: { $ref: 'location' },
    name: { type: 'string' },
    website: { type: 'string' },
  },
};
Run Code Online (Sandbox Code Playgroud)

在JSON Schema中是否有一种方法可以使用$ ref但是还要扩展它以使模式中的location属性company自动需要postalCode?我们当前的解决方案是基于location我们简单地更改required属性的位置创建第二个模式,但我希望有更好的方法.

谢谢.

esp*_*esp 5

您可以

{
  type: 'object',
  required: [ 'name', 'location' ],
  additionalProperties: false,
  properties: {
    location: {
      allOf: [
        { $ref: 'location' },
        { required: [ 'postalCode' ] }
      ]
    },
    name: { type: 'string' },
    website: { type: 'string' }
  }
}
Run Code Online (Sandbox Code Playgroud)