Reputation: 6206
Given a part of a schema called location
like this:
{
type: 'object',
required: [ 'country' ],
additionalProperties: false,
properties: {
country: {
enum: [ 'DE', 'CH', 'AT' ],
},
postalCode: { type: 'string' },
},
};
In most of our use cases a location is valid given only a country code. However we have a few occasions where we have to require a ZIP code as well.
A company in our case for example will always require a postalCode. Our previous location
schema does not enforce this of course. Other schemas require location objects that do not enforce presence of a postal code. This is our company schema:
{
type: 'object',
required: [ 'name', 'location' ],
additionalProperties: false,
properties: {
location: { $ref: 'location' },
name: { type: 'string' },
website: { type: 'string' },
},
};
Is there a way in JSON Schema to use a $ref but also extend it so that the location
property in the company
schema will automatically require a postalCode
? Our current solution is to create a second schema based on location
where we simply changed the required
attribute, but I'm hoping there is a better way.
Thank you.
Upvotes: 5
Views: 3820
Reputation: 7687
You can
{
type: 'object',
required: [ 'name', 'location' ],
additionalProperties: false,
properties: {
location: {
allOf: [
{ $ref: 'location' },
{ required: [ 'postalCode' ] }
]
},
name: { type: 'string' },
website: { type: 'string' }
}
}
Upvotes: 12