Skip to content

Proposal: Add propertyDiscriminator keyword (aka discriminator)  #1413

Closed
@xiaoxiangmoe

Description

@xiaoxiangmoe

The pattern of using oneOf to describe a choice between two types has become ubiquitous.

{
  "oneOf": [
    { "$ref": "#/$defs/aaa" },
    { "$ref": "#/$defs/bbb" }
  ]
}

However, this pattern is also notorious for its many shortcomings. There is a better way to describe this kind of constraint that doesn't have all the problems of the oneOf pattern, but it's verbose, error prone, and not particularly intuitive.

{
  "allOf": [
    {
      "if": {
        "properties": {
          "foo": { "const": "aaa" }
        },
        "required": ["foo"]
      },
      "then": { "$ref": "#/$defs/foo-aaa" }
    },
    {
      "if": {
        "properties": {
          "foo": { "const": "bbb" }
        },
        "required": ["foo"]
      },
      "then": { "$ref": "#/$defs/foo-bbb" }
    }
  ]
}

But this is too complicated. We may simplify this.

{
  "propertyDiscriminator": {
    "foo": [
      [
        "aaa",
        {
          "$ref": "#/$defs/foo-aaa"
        }
      ],
      [
        "bbb",
        {
          "$ref": "#/$defs/foo-bbb"
        }
      ]
    ]
  }
}

releated issue : #1082 (comment)

The difference between #1082 and this proposal is —— that issue only support string as discriminator.
This proposal is a little more complicated. But it would accept any json value here.

For example:

{
  "propertyDiscriminator": {
    "foo": [
      [
        2,
        {
          "$ref": "#/$defs/foo-aaa"
        }
      ],
      [
        3,
        {
          "$ref": "#/$defs/foo-bbb"
        }
      ]
    ]
  }
}

cc @jdesrosiers @gregsdennis

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    Closed

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions