数据:
{
"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": ????
}
}
您可以使用一些验证程序支持的自定义关键字来定义其他数据约束,例如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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句