jsonjsonschemajson-schema-validator

Json schema array of objects (where objects must be the same)


Trying to create a JSON schema, cannot figure out how to control that an object of type array contains sub-objects that must be a certain way. The thing is that I do not know how many sub objects I will have.

Oversimplified, I have this json:

{
  "Fuses":[
    {
        "Foo": 80
    },
    {
        "Foo": 20
    }
  ]
}

If I generate a schema for this, either it hard-codes that there will be two sub-objects containing "Foo" or I just leave one like:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "Fuses": {
      "type": "array",
      "items": [
        {
          "type": "object",
          "properties": {
            "Foo": {
              "type": "integer"
            }
          },
          "required": [
            "Foo"
          ]
        }
      ]
    }
  },
  "required": [
    "Fuses"
  ]
}

but then this would be valid, (which I do not want to):

{
  "Fuses":[
    {
        "Foo": 80
    },
    {
        "fooXYSCs": "whatever"
    }
  ]
}

I want to allow "Fuses" to have as many sub-objects in the array as wanted, but each of them must be as "Foo": integer (and required obv).


Solution

  • Your issue is that your schema describe an array of exactly one element.

    For example this:

    {
      "type": "array",
      "items": [
        { "const": 42 }
      ]
    }
    

    Is the same as this:

    {
      "type": "array",
      "minItems": 1,
      "maxItems": 1,
      "items": [
        { "const": 42 }
      ]
    }
    

    Which will validate this and only this array: [42]

    If your array can contain zero or more elements of the same shape this is how I would do it:

    {
      "type": "array",
      "items": {
        "const": 42
      }
    }
    

    Which would validate [], [42], [42, 42], [42, 42, 42], ... but not [42, 43] for example.

    So to answer your question your schema should be:

    {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "type": "object",
      "properties": {
        "Fuses": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "Foo": {
                "type": "integer"
              }
            },
            "required": [
              "Foo"
            ]
          }
        }
      },
      "required": [
        "Fuses"
      ]
    }