Tom
Tom

Reputation: 1271

How to correctly reference an external JSON Schema?

I have a JSON Schema for DNS records (dns-record.schema.json) that I want to consume in a separate JSON Schema (dns-tool.schema.json) for a tool I am trying to build. What is the correct way to reference the dns-record schema?

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "dns-tool.schema.json",
  "title": "Zone Config Schema",
  "type": "object",
  "properties": {
    "records": {
      "type": "array",
      "items": {
        {
          "$ref": "dns-record.schema.json"
        }
      }
    }
  }
}

These schemas are being consumed via VS Code's JSON service that provide intellisense and are expected to validate data at runtime, but the software is not yet written so in addition to the VS Code "test" I try to compilie the schema with ajv-cli:

ajv "compile" "--verbose" "true" "-s" "dns-tool.schema.json"

schema dns-tool.schema.json is invalid error: can't resolve reference dns-record.schema.json from id dns-tool.schema.json

The files are all in the project root and not an issue of the wrong path.

Upvotes: 1

Views: 554

Answers (2)

Tom
Tom

Reputation: 1271

Two things going-on:

  1. ajv-cli only references schema by ID so the referenced files must provided with -r ajv compile --verbose true -s dns-tool.schema.json -r dns-record.schema.json

  2. VSCODE references by file name.

Solution: Set the ID to the file name, do not use file:// in the URI. This is only a partial solution because the schemata have to be in the same dir - so even though the answer comes from the OP, I'm not selecting it has THE answer.

Upvotes: 1

Jeremy Fiel
Jeremy Fiel

Reputation: 3219

The one thing you may need to do with local files is require() or import the file in your js.

const otherSchema = require('./mySchema.json')
const Ajv = require('ajv')
const mainSchema = {
    "$id": "test.json",
    "$schema": "http://json-schema.org/draft-07/schema#",
    "description": "This is a schema",
    "type": "object",
    "properties": {
      "name": { "$ref": "mySchema.json"}
    }
}

try {
    const ajv = new Ajv({ "strict": false });
    ajv.addSchema(otherSchema, "test");
    const validate = ajv.compile(mainSchema);
    console.log(validate = {
        valid: validate
    });
} catch (err) {
    console.error(validate = {
        valid: false,
        message: err.message
    })
}
#separate file  mySchema.json
{
    "$schema":"http://json-schema.org/draft-07/schema#",
    "$id": "mySchema.json",
    "type": "string"
}

Upvotes: 0

Related Questions