50

I have a json object that can contain any number of nested objects with certain specification, for example:

{
  "Bob": {
    "age": "42",
    "gender": "male"
  },
  "Alice": {
    "age": "37",
    "gender": "female"
  }
}

And would like to have a schema looking something like:

{
  "type": "object",
  "propertySchema": {
    "type": "object",
    "required": [
      "age",
      "gender"
    ],
    "properties": {
      "age": {
        "type": "string"
      },
      "gender": {
        "type": "string"
      }
    }
  }
}

I know that I can turn that into array and push 'name' inside the objects. In that case my schema would look like:

{
  "type": "array",
  "items": {
    "type": "object",
    "required": [
      "name",
      "age",
      "gender"
    ],
    "properties": {
      "name": {
        "type": "string"
      },
      "age": {
        "type": "string"
      },
      "gender": {
        "type": "string"
      }
    }
  }
}

but I would like to have a dictionary-like structure. Is it possible to make such schema?

jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
ironic
  • 8,368
  • 7
  • 35
  • 44

1 Answers1

79

additionalProperties is your keyword:

{
    "type" : "object",
    "additionalProperties" : {
        "type" : "object",
        "required" : [
            "age",
            "gender"
        ],
        "properties" : {
            "age" : {
                "type" : "string"
            },
            "gender" : {
                "type" : "string"
            }
        }
    }
}

additionalProperties can have the following values with different meanings:

  • "additionalProperties": false No more properties are allowed at all.
  • "additionalProperties": true Other properties are allowed. This is the default behavior.
  • "additionalProperties": {"type": "string"} Additional properties (of arbitrary name) are allowed, as long as their value follows the given type ("string" here).
  • "additionalProperties": {*any schema*} Additional properties must satisfy the provided schema, such as the example provided above.
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
  • 2
    Thanks for nice answer. I added few lines explaining different meanings of "additionalProperties". – Jan Vlcinsky Aug 26 '15 at 10:29
  • Thanks @JanVlcinsky for enhancing the answer (although using titles for code excerpts seems a bit excessive for me). – jruizaranguren Aug 26 '15 at 10:40
  • 1
    Feel free to edit it as you prefer. That was the reason I have notified you. I often use headers to deliver key information in a bit more visual way, but it may feel sometime to much, I agree. – Jan Vlcinsky Aug 26 '15 at 11:27