Wanderer
Wanderer

Reputation: 590

Cannot resolve reference in JSON Schema using AJV - CLI

I'm trying to build a JSON schema (draft-06) for an existing JSON data file. The schema has gotten to big to fit in a single file and I am trying to break it up into multiple files. However I keep getting the error can't resovle refrence sectionTableSchema.txt from id http://somesite/section

I've made the following files and placed them in the same directory. These files are not hosted on a webserver.

settingsSchema.txt:

{
  "title":"Settings",
  "$schema":"http://json-schema.org/draft-06/schema#",
  "$id":"http://somesite/settingsSchema.txt",
  "properties":{
    "section":{
      ...
      ...
      ...
      "$id":"/section",
      "items":{
        "oneOf":[
          {"$ref":"#/sectionTableSchema.txt"},
          {"$ref":"#/sectionNonTableSchema.txt"}
        ]
      },
      "type":"array"
    }
  },
  "type":"object"
}

sectionTableSchema.txt

{
  "$schema":"http://json-schema.org/draft-06/schema#",
  "$id":"http://somesite/sectionTableSchema.txt",
  "definitions":{},
  "properties":{
    ....
    ....
    ....
  }
  "type":"object"
}

I think part of my issue is that I don't understand the $id and $ref keywords enough to know what is going on between absolute uri, relative uri, json-pointers and the like.

Upvotes: 3

Views: 2101

Answers (1)

N. Kudryavtsev
N. Kudryavtsev

Reputation: 4071

What happens?

In the OP's example "$ref":"#/sectionTableSchema.txt" means "inside current schema file, get JSON property called sectionTableSchema.txt from root element".


How $ref works?

$ref can be presented in two parts:

  • Before "#" sign you can specify URI (in simple words, a path) of schema file. If you start $ref from "#" sign and, therefore, don't provide URI of schema file, this means you want to take schemas from current file.
  • After "#" sign you can provide a JSON pointer, e. g. a path to the property in JSON that is located in specified file (or current file, depending on provided schema URI before "#" sign).

The same information can be found in documentation.


How to reference other file correctly?

As I understand, JSON Schema drafts say you can specify a valid URI to schema file. But URIs cannot be relative, so there is no standard-defined way of referencing files with relative paths. However, in practice a lot of tools provide abilities to do this, though they are not a part of the standard and may differ from tool to tool.

In AJV you can write your reference as "$ref":"ANY-ID-YOU-WANT" and use ajv.addSchema(schemaJson, 'ANY-ID-YOU-WANT') method, where schemaJson is a variable with require'd sectionTableSchema.txt content.

Upvotes: 3

Related Questions