Mihail Kuznetsov Mihail Kuznetsov - 28 days ago 5
JSON Question

Error: can't resolve reference error.json from id #

I not understand how correct reference to other schema.
I used ajv, and have next two schema

First schema incorrect-email.json:

{
"title": "Не корректный email",
"properties": {
"status": {
"description": "Статус операции",
"type": "integer",
"enum": [68]
},
"error": {
"$ref":"error.json"
}
},
"required":["status", "error"],
"additionalProperties": false
}


Second schema error.json:

{
"type": "array",
"minItems": 2,
"items": {
"type": "object",
"properties": {
"description_ru": {
"description": "Информация об ошибке на русском языке",
"type": "string"
},
"description_en": {
"description": "Информация об ошибке на английском языке",
"type": "string"
}
},
"additionalProperties": false
}
}


After run test i get this error


Error: can't resolve reference error.json from id #
Mine validation method:


var valid = ajv.validate(require("../schema/login/incorrect-email.json"), data);


Me need reference to local schema error.json, not remote server and etc.
Please tell me, where i can added id in this schemas and $ref for correct parse with ajv

esp esp
Answer

Without changing schema files you can do:

ajv.addSchema(require('./incorrect-email.json', 'incorrect-email.json'));
ajv.addSchema(require('./error.json'), 'error.json');
var valid = ajv.validate('incorrect-email.json', data);

Instead of specifying schema IDs in addSchema calls you can specify ID attributes in schemas themselves (it is recommended). In any case Ajv, by default, will not use any IO to load schemas, schemas have to be preloaded with addSchema method. You can dynamically (and asynchronously) load schemas when you use compileAsync method, but you have to specify your loading mechanism yourself (can be anything - fs, http, etc.).