How to use definitions in JSON schema (draft-04)

nishant picture nishant · Aug 22, 2013 · Viewed 19.7k times · Source

The rest service response I am working with is similar to following example, I have only included 3 fields here but there are many more:

{
    "results": [
        {
            "type": "Person",
            "name": "Mr Bean",
            "dateOfBirth": "14 Dec 1981"
        },
        {
            "type": "Company",
            "name": "Pi",
            "tradingName": "Pi Engineering Limited"
        }
    ]
}

I want to write a JSON schema file for above (draft-04) which will explicitly specify that:

if type == Person then list of required properties is ["type", "name", "dateOfBirth", etc] 
OR
if type == "Company" then list of required properties is ["type", "name", "tradingName", etc]

However am unable to find any documentation or example of how to do it.

Currently my JSON schema looks like following:

{
    "$schema": "http://json-schema.org/draft-04/schema",
    "type": "object",
    "required": ["results" ],
    "properties": {
        "results": {
            "type": "array",
            "items": {
                "type": "object",
                "required": ["type", "name"],
                "properties": {
                    "type": { "type": "string" },
                    "name": { "type": "string" },
                    "dateOfBirth": { "type": "string" },
                    "tradingName": { "type": "string" }
                }
            }
        }
    }
}

Any pointers/examples of how I should handle this.

Answer

jruizaranguren picture jruizaranguren · Aug 22, 2013

I think the recommended approach is the one shown in Json-Schema web, Example2. You need to use an enum to select schemas "by value". In your case it would be something like:

{
    "type": "object",
    "required": [ "results" ],
    "properties": {
        "results": {
            "type": "array",
            "items": {
                "oneOf": [
                    { "$ref": "#/definitions/person" },
                    { "$ref": "#/definitions/company" }
                ]
            }
        }
    },
    "definitions": {
        "person": {
            "properties": {
                "type": { "enum": [ "person" ] },
                "name": {"type": "string" },
                "dateOfBirth": {"type":"string"}
            },
            "required": [ "type", "name", "dateOfBirth" ],
            "additionalProperties": false
        },
        "company": {
            "properties": {
                "type": { "enum": [ "company" ] },
                . . . 
            }        
        }
    }
}