Reputation:
I am currently developing a JSON schema extractor for MongoDB.
For example, I have the following JSON documents (taken from https://github.com/variety/)
{"name": "Tom", "pets": ["monkey", "fish"]}
{"name": "Harry", "pets": "egret"}
As you can see, pets can be both an array and a string. Is there a JSON Schema that allows for both these documents?
Upvotes: 1
Views: 456
Reputation: 12873
Absolutely. In fact, for this there are two ways:
#1) Multiple entries in "type"
The "type"
keyword in your schema can be an array:
{
"type": ["string", "array"],
"items": {
"type": "string"
}
}
Here, the data is allowed to be either a string or an array. Because the "items"
keyword is only used if the data is an array, then this says that the data can be either a string or an array of strings.
#2) Using "oneOf"
The above works for the simple case. However, in the general case of "this could be A or B", then you can use "oneOf"
:
{
"oneOf": [
{
"type": "string"
},
{
"type": "array",
"items": {
"type": "string"
}
}
]
}
This is more verbose - the first option is nice and simple. However, this option can be used if your constraints are more complicated (e.g. "data can be either an array of booleans, or an array of numbers").
Upvotes: 3