AaronT
AaronT

Reputation: 21

Can JSON schema validate exactly one property contains a certain property?

I was trying to come up with a schema to validate JSON objects like the following:

{
    "id":"some_id",
    "properties":{
        "A":{
            "name":"a",
            "isindex":true
        },
        "B":{
            "name":"b"
        },
        "C":{
            "name":"c"
        }
    }
}

The deal is:

  1. properties A, B, C are not known beforehand and can be any strings.
  2. One and only one of the properties (A, B, C ...) has in its value a "isindex":true key-value pair to indicate the property will be used as a index. That is to say the following is invalid.

.

{
   "id":"some_id",
   "properties":{
     "A":{
        "type":"string",
        "isindex":true
     },
     "B":{
     "type":"string"
     },
     "C":{
        "type":"array",
         "isindex":true
     }
  }
}

Actually, I am not sure if the JSON schema is the right tool for for this.

Any or all help is appreciated!

Upvotes: 0

Views: 1340

Answers (1)

Jason Desrosiers
Jason Desrosiers

Reputation: 24489

JSON Schema is the right tool for this kind of thing, but you have stumbled on a specific case that it doesn't handle. You can assert that at least one matches a particular schema, but you can't assert that one and only one matches.

The best thing you can do is change your data structure to something like this ...

{
  "id":"some_id",
  "properties":{
    "A":{
      "name":"a"
    },
    "B":{
      "name":"b"
    },
    "C":{
      "name":"c"
    }
  },
  "index": "A"
}

Upvotes: 2

Related Questions