数据:
{
"languages": ['en', 'ch'],
"file": {
"en": "file1",
"ch": "file2"
}
}
如何定义一个模式,通过"语言"来验证文件属性中的键名。属性?
{
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "",
"type": "object",
"properties": {
"languages": {
"type": "array",
"items": {
"type": "string"
}
},
"file": {
"type": "object",
"properties": ????
}
}
答案 0 :(得分:2)
您可以使用某些验证程序支持的自定义关键字定义其他数据约束,例如: Ajv(我是作者):
var Ajv = require('ajv');
var ajv = new Ajv;
ajv.addKeyword('validateLocales', {
type: 'object',
compile: function(schema) {
return function(data, dataPath, parentData) {
for (var prop in data) {
if (parentData[schema.localesProperty].indexOf(prop) == -1) {
return false;
}
}
return true;
}
},
metaSchema: {
type: 'object',
properties: {
localesProperty: { type: 'string' }
},
additionalProperties: false
}
});
var schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"languages": {
"type": "array",
"items": { "type": "string" }
},
"file": {
"type": "object",
"validateLocales": {
"localesProperty": "languages"
},
"additionalProperties": { "type": "string" }
}
}
};
var data = {
"languages": ['en', 'ch'],
"file": {
"en": "file1",
"ch": "file2"
}
};
var validate = ajv.compile(schema);
console.log(validate(data));
答案 1 :(得分:0)
绝对不可能用json架构表达这样的约束。