2016-10-28 119 views
3

以下是我试图编译并用于验证的JSON模式的示例。为了完成这个,我使用'ajv' npm module为什么Ajv在编译期间无法解析引用?

这里是我运行的代码......

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 # 

有没有其他人遇到这种问题?任何想法我可能做错了什么?

回答

1

你的参考是不正确的(虽然它是有效的),它应该是#/定义/电话

另外,使其工作,你可以添加"id": "#definitions/phone"电话架构里面,但更常见的是使用"id": "#phone"(和更新$ refs)。

+0

这确实解决了这个问题,但你能解释为什么'#/ definitions/phone'工作和'#definitions/phone'不能?否则,开发人员的所有文档都会暗示。谢谢! – ra9r

+0

你引用了哪些文档?我是开发btw :)这是规范,当前模式中的引用是#后面跟着JSON指针,JSON指针从“/”开始 – esp

+0

伟大的图书馆,感谢您为我们其他人贡献它。关于你的问题,我可以发誓,我在json-schema.org网站上的例子中看到了这一点,但在我的生活中,我找不到任何例子作为证明。所以我必须失明或疯狂。感谢您的及时回复。 – ra9r

相关问题