Question

I have to validate JSONs that look like:

{
  "propertyName1" : "value",
  "propertyName2" : ["value1", "value2"],
  "propertyName3" : { "operator1" : "value" },
  "propertyName4" : { "operator2" : ["value1", "value2"] },
  ...
}

So the propertyName is an arbitrary key, and operators are defined.

I think I should use a schema like:

{
    "id" : "urn:my_arbitrary_json#",
    "type" : "object",
    "required" : false,
    "additionalProperties" : {
        "id" : "urn:my_arbitrary_key#",
        "type" : "object",
        "required" : true,
        "properties" : {
            "operator1" : { ... },
            "operator2" : { ... }
        }
    }
}

However, this schema lacks definition for propertyName1 and propertyName2 cases. I would like to define an array to validate different types of additionalProperties, but this is not correct according to specification. Is there any way to validate such a JSON?

Was it helpful?

Solution

If a given piece of data can be many different shapes, then you can use oneOf or anyOf. For instance here you could have:

{
    "type" : "object",
    "additionalProperties" : {
        "oneOf": [
            {... string ...},
            {... array of strings ...},
            ...
        ]
    }
}

Actually, because the options here are all distinct types, you can simply have multiple entries in type instead:

{
    "type" : "object",
    "additionalProperties" : {
        "type": ["string", "array", "object"],
        "items": {"type": "string", ...}, // constraints if it's an array
        "properties": {...} // properties if it's an object
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top