【问题标题】:Why is Ajv unable to resolve reference during compile?为什么 Ajv 在编译期间无法解析引用?
【发布时间】:2017-03-11 10:10:17
【问题描述】:

以下是我尝试编译并用于验证的 JSON 模式示例。为此,我使用'ajv' npm module

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

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);

当我运行这段代码时,我得到了以下异常..

Error: can't resolve reference #definitions/phone from id #

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

【问题讨论】:

    标签: node.js jsonschema ajv


    【解决方案1】:

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

    或者,要使其正常工作,您可以在电话模式中添加"id": "#definitions/phone",但更常见的是使用"id": "#phone"(并且也更新$refs)。

    【讨论】:

    • 这确实解决了问题,但您能解释一下为什么#/definitions/phone 有效而#definitions/phone 无效吗?开发人员的所有文档都会暗示其他情况。谢谢!
    • 您参考什么文档?我是开发人员顺便说一句:) 这是规范,当前模式中的引用是 # 后跟 JSON 指针,JSON 指针从“/”开始
    • 很棒的库,感谢您为我们其他人贡献它。至于您的问题,我可以发誓我在 json-schema.org 网站上的示例中看到了这一点,但对于我的生活,我找不到任何示例作为证据。所以我一定是失明或疯了。感谢您的及时回复。
    猜你喜欢
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 2018-03-19
    • 2014-09-03
    • 1970-01-01
    相关资源
    最近更新 更多