Defining custom JSON schema type

2,343 views
Skip to first unread message

Donal Murtagh

unread,
Nov 30, 2016, 12:01:31 PM11/30/16
to JSON Schema
Given a JSON schema such as

    {
     
"type": "object",
     
"properties": {
       
"ageInYears": {
         
"type": "integer",
         
"minimum": 0,
         
"maximum": 120
       
},
       
"spouseAgeInYears": {
         
"type": "integer",
         
"minimum": 0,
         
"maximum": 120
       
},
       
"childAgeInYears": {
         
"type": "integer",
         
"minimum": 0,
         
"maximum": 120
       
}
     
}
   
}

Notice that the attributes of each property are identical, so to avoid this repetition I'd like to somehow define a custom type

    "age": {
     
"type": "integer",
     
"minimum": 0,
     
"maximum": 120
   
}

and then refer to it within my schema, e.g.

    {
     
"type": "object",
     
"properties": {
       
"ageInYears": {
         
"type": "age"
       
},
       
"spouseAgeInYears": {
         
"type": "age"
       
},
       
"childAgeInYears": {
         
"type": "age"
       
}
     
}
   
}


It seems that the purpose of the "format" attribute is to implement this sort of type customisation, but I can't find any examples of how to define a custom "format" value.

Henry Andrews

unread,
Nov 30, 2016, 12:57:38 PM11/30/16
to JSON Schema
Hi Donal,
  You want "definitions" and "$ref":

{
   
"definitions": {

       
"ageInYears": {
           
"type": "integer",
           
"minimum": 0,
           
"maximum": 120
       
}
   
},
   
"type": "object",
   
"properties": {

       
"ageInYears": {"$ref": "#/definitions/ageInYears"},
       
"spouseAgeInYears": {"$ref": "#/definitions/ageInYears"},
       
"childAgeInYears": {"$ref": "#/definitions/ageInYears"}
   
}
}

Custom formats are more for things that can't be fully described in schema, which is why they are more about semantics than structure.

thanks,
-henry
Reply all
Reply to author
Forward
0 new messages