为什么 Ajv 在编译期间无法解析引用?

ra9*_*a9r 5 jsonschema node.js ajv

以下是我尝试编译并用于验证的 JSON 架构示例。为了实现这一点,我使用“ajv”npm 模块

这是我正在运行的代码...

var ajv = require('ajv')();

var contactSchema = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Contact",
    "type": "object",
    "additionalProperties": false,
    "properties": {
        "work": { "$ref": "#definitions/phone" },
        "home": { "$ref": "#definitions/phone" },
    },
    "definitions": {
        "phone": {
            "type": "object",
            "required": ["number"],
            "properties": {
                "number": { "type": "string" },
                "extension": { "type": "string" }
            }
        }
    }
};

var validator = ajv.compile(contactSchema);
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,出现以下异常..

Error: can't resolve reference #definitions/phone from id #
Run Code Online (Sandbox Code Playgroud)

还有其他人遇到过这种问题吗?知道我可能做错了什么吗?

esp*_*esp 3

您的参考不正确(尽管它是有效的),它应该是#/definitions/phone

或者,为了使其工作,您可以添加"id": "#definitions/phone"内部电话模式,但它更常用"id": "#phone"(并且也更新 $refs)。