baynezy baynezy - 3 months ago 17
JSON Question

JSONSchema how to define a schema for a dynamic object

I have a JSON response that I am trying to create a JSONSchema for

{
"gauges": {
"foo": {
"value": 1234
},
"bar": {
"value": 12.44
}
}
}


It is important to know that the objects in the associative array
gauges
are dynamically generated so there can be zero to many. Each object in
gauges
will always have a
value
property and it will always be a number.

So each these are valid

Example 1



{
"gauges": {
"foo": {
"value": 1234
}
}
}


Example 2



{
"gauges": {
"dave": {
"value": 0.44
},
"tommy": {
"value": 12
},
"steve": {
"value": 99999
}
}
}


Example 3



{
"gauges": {}
}


I have looked though the specification and if this was an array I know I could use
anyOf
but I am unsure how to do this or if it is even possible.

NB I cannot change the format of the JSON

Answer

Conceptually what you want is an object representing a Typed Map.

The difficulty is that you have no named property to put your specification in the schema, but in that case You can use "additionalProperties"

{
"type": "object",
  "properties": {
    "gauges": {
      "type": "object",
      "additionalProperties": {
        "type": "object",
        "properties": {
           "value": {"type": "number"}
        }
      } 
    }
  }
}

"gauges" property is defined as an object in which every "additionalProperties" will have a type containing a value of type number.

Note: In java you would serialize it to a Map<String,Value> with Value the classe containing a value. (don't know for other typed language, but I am open to suggestions)

This answer point to an analog solution How to define JSON Schema for Map<String, Integer>?