0

I am struggling to define a JSON schema to require one parameter and, at most one of the two optional parameters. In other words, the following should be legal:

{
  "a_req" : "foo"
}
{
  "a_req" : "foo",
  "b_opt" : "bar"
}
{
  "a_req" : "foo",
  "c_opt" : "baz"
}

But the following should be illegal

{
  "a_req" : "foo",
  "b_opt" : "bar",
  "c_opt" : "baz"
}

I've tried many permutations of the following, but it doesn't seem to work.

"oneOf" : [
    {
        "required": ["a_req"],
        "not" : {"required" : ["b_opt", "c_opt"]}
    },
    {
        "required": ["a_req", "b_opt"],
        "not" : {"required" : ["c_opt"]}
    },
    {
        "required": ["a_req", "c_opt"],
        "not" : {"required" : ["b_opt"]}
    },
]
Paul Grinberg
  • 1,184
  • 14
  • 37
  • `maxProperties: 2` might work for you here. don't forget to add `additionalProperties: false` also. – Ether Jan 17 '22 at 19:03
  • The answer [here](https://stackoverflow.com/questions/28162509/mutually-exclusive-property-groups) may be useful to you. – Rami Jan 06 '23 at 14:55

1 Answers1

0

Here's what I finally came up with

{
    "allOf" : [
        {
            "required": ["a_req"],
        },
        {
            "not" : {
                "anyOf" : [
                    {"required" : ["b_opt", "c_opt"]}
                ]
            }
        }
    ]
}
Paul Grinberg
  • 1,184
  • 14
  • 37
  • 1
    Yup, that works. you can also remove that `allOf` entirely, as the two halves of the `allOf` do not use any of the same keywords. And an `anyOf` with just one clause is the same as not having the `allOf` at all. So, simplified, that would be: `{ "required": ["a_req"], "not": { "required": ["b_opt", "c_opt"] } }` – Ether Jan 17 '22 at 19:04