2014-11-13 41 views
1

我想引用父級json模式中的子模式。這是一個名爲child.jsonJSON模式:引用本地子模式

{ 
"$schema": "http://json-schema.org/draft-04/schema#", 
"title": "Child", 
"description": "Child schema", 
"type": "object", 
"properties": { 
    "name": {"type": "string"}, 
    "age": {"type": "integer"} 
}} 

孩子架構,這裏是名爲parent.json父架構和所有的兩個文件是在同一文件夾。我想要參考子模式,我喜歡這樣的:

{ 
"$schema": "http://json-schema.org/draft-04/schema#", 
"title": "Parent", 
"description": "Parent schema", 
"type": "object", 
"properties": { 
"allOf": [ 
    { 
     "$ref": "file://child.json" 
    } 
], 
"adresse": {"type": "string"} 
}} 

我有一個錯誤,說沒有找到文件child.json。我測試過很多次,但任何人都在工作。
感謝您的幫助

+0

這可能取決於您使用的庫。 Json-schema依靠ref值成爲一個有效的URI。您是否嘗試過使用「child.json」或「file:child.json」?你正在使用哪個庫,以及如何加載模式? – jruizaranguren

回答

2

我找到了解決我的問題的方案。這裏是解決方案
上下文是我們總是有兩個模式:父母和孩子。家長必須包括在他的財產這樣的面值爲例的一個子模式:

"myChild": { 
     "$ref": "child" //referencing to child schema 
} 

並在他的初子模式,你必須把一個ID就可以像這樣

現在
{ 
    "id": "child", //important thing not to forget 
    "$schema": "http://json-schema.org/draft-04/schema#" 
    //other codes goes here 
} 

與jaySchema驗證,你會做這樣的

var js = new JaySchema(); 
var childSchema = require('./child.json'); 
var parentSchema = require('./parent.json'); 

//other codes goes here 
js.register(childSchema); //important thing not to forget 
js.validate(req.body, schema, function(err) { 
    if (err) //your codes for err 
}); 

而這一切都。 :-D
這是我的解決方案,但它不是最好的,我希望它會有所幫助。感謝所有您的答案

1

$ref值可以是URI引用 - 它們不需要是絕對URI。所以在這裏,你應該能夠使用:

{"$ref": "child.json"} 

它應該適當地解決。

+0

如果您在瀏覽器中,值得注意的是,由於安全限制,無法使用AJAX獲取'file://'URL。 – cloudfeet

+0

我已經這樣做了,但它不工作,我仍然不知道爲什麼 –

+0

是否可以粘貼實際的錯誤?你是在瀏覽器中從JS做到這一點? – cloudfeet

0

如果你的父母和孩子模式在類路徑中,並在同一個地方,然後做的最好的事情就是使用自定義resource URI方案以絕對URI來加載它:

final JsonSchema schema = factory.getJsonSchema("resource:/path/to/parent.json"); 

然後你可以使用{ "$ref": "child.json" }引用您的子模式(因爲JSON引用相對於當前模式的URI已解析)

+0

我使用模塊jaySchema並獲取模式,我只是做類似的事情「var schema = require('../../ contract/entities/operation.json');」然後我調用該函數進行驗證:「js.validate(req.body,schema)」。這是一個好方法嗎? –

+0

Hmmwait ...這段軟件是否真的使用json-schema-validator? – fge

+0

weah它基於json-schema-validator –