Search code examples
jsonjsonschemarapidjson

Is it valid json (schema) to say that an element can be a single item or an array


Is it possible to specify that a particular json value can be either a single element or an array?

E.g. Can both of following json documents be valid according to a given single json schema.

"person": {
    "name": "john",
    "friends": "jack"
}

"person": {
    "name": "john",
    "friends": ["jack", "jill"]
}

It's certainly possible (I believe) if you ignore the concept of schema, and simply when you are parsing using a parser such as rapidjson, to simply check if the element is an array or not before reading the contents.

What I want to know is, if I take this approach, will it be a problem if I want to specify a json schema for it later on?


Solution

  • In JSON schema you can specify either one type that an item must match, or an array of types of which the item must match at least one (plus a few other possibilities).

    So yes, you can have a schema that says the "friends" value is either a string, or an array of strings.

    Obviously this means that client code and server code need to distinguish both cases and have different code for each case; you might consider sending an array with one string instead of someone has exactly one friend to simplify all code.