tok
tok

Reputation: 981

Structuring JSON schema with hierarchical definitions

I'm new in writing JSON schemas. I thought I could use the following structure in my schema file. What do you think, is this feasible?

{
    "properties": {
        "my_object": {
            "$ref": "#/definitions/my_object"
        }
    },
    "formats": {
        "language": {
            "type": "string",
            "pattern": "^[a-z]{2}-[A-Z]{2}$"
        },
        "zipcode": {
            "type": "string",
            "pattern": "\\d{5}-\\d{4}|\\d{5}"
        }
    },
    "definitions": {
        "my_object": {
            "type": "object",
            "properties": {
                "language": {"$ref": "#/formats/language"},
                "zipcode": {"$ref": "#/formats/zipcode"}
            }
        }
    }
}

The top level only contains references to objects under definition. Since I need some type & pattern pairs more than once I put them under formats.

Is definitions a key word in JSON schema? At least it is widely used in examples. Is it ok to add your own "key words" like formats here or should everything go under definitions?

Upvotes: 1

Views: 617

Answers (1)

Byted
Byted

Reputation: 657

While a lot of examples indeed use definitions it is outdated and the recommended way is to use $defs instead. Other keys are still supported to be backwards compatible. See here for more

Thus, I'd recommend keeping all sub-schemas in the $defs object. It is still possible to to group semantically related sub-schemas inside $defs so if you insist on keeping the the distinction you can do something like this:

{
   "properties":{
      "my_object":{
         "$ref":"#/$defs/my_object"
      }
   },
   "$defs":{
      "my_object":{
         "type":"object",
         "properties":{
            "language":{
               "$ref":"#/$defs/formats/language"
            },
            "zipcode":{
               "$ref":"#/$defs/formats/zipcode"
            }
         }
      },
      "formats":{
         "language":{
            "type":"string",
            "pattern":"^[a-z]{2}-[A-Z]{2}$"
         },
         "zipcode":{
            "type":"string",
            "pattern":"\\d{5}-\\d{4}|\\d{5}"
         }
      }
   }
}

Upvotes: 3

Related Questions