How do you reference another schema from a schema


#1

I am trying to reference another schema so that i dont have to retype the entire json document again with all of the properties (and also so i dont have to worry about updating multiple places when i need to add/edit/remove a property)

suppose i have

schemas:

carModel: |

    "$schema": "http://json-schema.org/draft-04/schema",
    "type": "object",
    "properties":
    {
      "name": { "type": "string", "required": false },
      "year": { "type": "integer", "required": false }
    }

carInfo: |

    "$schema": "http://json-schema.org/draft-04/schema",
    "type": "object",
    "properties":
    {
      "color": { "type": "string", "required": false },
      "model": { "type": "carModel", "required": false } <-- This DOES NOT work
    }

How do i properly reference “model” in carInfo to the carModel object so that all of the properties get picked up when i reference the carInfo object?


#2

I think it should be

“model”: {
"$ref": “http://xyz.com/schema/carModel#”, “required”: false }


#3

Hi @GPancorvo, @Bhargava is right. Please check http://json-schema.org/latest/json-schema-core.html#anchor30 for more information.


#4

You can try csonschema, it let you write jsonschema simpler and with support of reusable schemas.

First, install it through npm

$ npm install -g csonschema-cli

Then, create schemas files in cson/YAML format.

carModel.csonschema

name: 'string'
year: 'interger'

carInfo.csonschema

$defs:
    carModel:
        $include: 'carModel.csonschema'
color: 'string'
model: 'carModel'

Convert csonschema to jsonschema.

$ csonschema carModel.csonschema >carModel.json
$ csonschema carInfo.csonschema >carInfo.json

Finally, include generated jsonschemas in RAML

schema: !include carModel.json

There is also a grunt plugin grunt-csonschema to automated the compiling process.


#5

I tried something like what @Bhargava suggested or using examples from the json-schema reference and nothing seems to work … at least in the creator tool.

When I tried putting ‘sub’ schemas in a ‘definitions’ object as they had on json-schema RAML creator tool wouldn’t validate it saying it had to be a string.

Basically I have a bunch of older Swagger 1.2 models which I am trying to figure out how to convert and re-use.


#6

The following article may be useful to you: http://json-schema.org/latest/json-schema-core.html#anchor30