cyberwombat
cyberwombat

Reputation: 40124

JSON schema - conditionally apply a $ref to a value based on the other value?

I am wanting to conditionally validate against a $ref based on another value in my schema.

items: {
    type: 'object',
    properties: {
      kind: { type: 'string', enum: ['foo', 'bar'] },
      //parameters: { $ref: 'foo.json#' } // This works
      parameters: {
        if: {
          kind: 'foo'
        },
        then: {
          $ref: 'foo.json#'
        }
      }
      // also tried   
      if: {
        kind: 'foo'
      },
      then: {
        parameters: { $ref: 'foo.json#' }
      }

I would like parameters to be validated against the foo.json reference whenever the value of kind is equal to foo (same with bar and bar.json). However the above is not working. Uncommenting out the commented section works so they are not equivalent.

How can I format this to conditionally apply a $ref to a value based on the other value?

I actually have about 10 different values for the type enum so if there is a cleaner way do this than if/else I am open.

Upvotes: 0

Views: 816

Answers (1)

cyberwombat
cyberwombat

Reputation: 40124

Ah got it....

items: {
  type: 'object',
  properties: {
    kind: { type: 'string', enum: ['foo', 'bar'] }
  },
  required: ['parameters'],
  if: {
    properties: { kind: { const: 'foo' } },
    required: ['kind']
  },
  then: {
    properties: {
      parameters: {
        $ref: 'fpp.json#'
      }
    }
  }

It's helpful for me to think that whatever is in if and else are essentially merged with the main schema.

Upvotes: 1

Related Questions