Ray Yun Ray Yun - 1 month ago 13
JSON Question

How to manage multiple JSON schema files?

I'm trying to validate my JSON API using node.js + json-schema.js from commonjs-utils. Just single validation was easy but could not find right way how to manage multiple schema files to enable referencing each other.

Suppose that I got two Models & two APIs.

// book
{
"type": "object",
"properties": {
"title": { "type": "string" },
"author": { "type": "string" }
}
}
// author
{
"type": "object",
"properties": {
"first_name": { "type": "string" },
"last_name": { "type": "string" }
}
}
// authors API
{
"type": "array",
"items": { "$ref": "author" }
}
// books API: list of books written by same author
{
"type": "object",
"properties": {
"author": { "$ref": "author" }
"books": { "type": "array", "items": { "$ref": "book" } }
}
}


Each schema should be divided in separate file and be online? Or Can I combine into single schema file like below? If it is possible, how can I reference local schema?

// single schema file {
"book": { ... },
"author": { ... },
"authors": { ... },
"books": { ... } }

Answer

In JSON Schemas, you can either put a schema per file and then access them using their URL (where you stored them), or a big schema with id tags supposed to name the branch you are one.

Here is for one big file:

{
"id":"#root",
"properties":{
    "book":{
      "type": "object",
      "id":"#book",
      "properties": {
          "title": { "type": "string" },
          "author": { "type": "string" }
      }
    }
    // author
    "author":{
      "type": "object",
      "id":"#author",
      "properties": {
          "first_name": { "type": "string" },
          "last_name": { "type": "string" }
      }
    }  
    // authors API
    "author_api":{
      "type": "array",
      "id":"#author_api",
      "items": { "$ref": "author" }
    }
    // books API: list of books written by same author
    "books_api"{
      "type": "object",
      "id":"#books_api",
      "properties": {
        "author": { "$ref": "author" } 
        "books": { "type": "array", "items": { "$ref": "book" } }
      }
    }
}
}

You can then validate reference your validator to one of those sub schema, defined by their id.

from the outside of your schema:

{"$ref":"url://to/your/schema#root/properties/book"}

is equivalent to

{"$ref":"url://to/your/schema#book"}

which is equivalent (from inside) to

{"$ref":#root/properties/book}

As (still from inside)

{"$ref":#book}

See my answer here for more information

Comments