在插入/更新数据库之前,我使用ajv来验证JSON数据模型。
今天我想使用这种结构:
const dataStructure = {
xxx1234: { mobile: "ios" },
yyy89B: { mobile: "android" }
};
我的键是动态的,因为它们是id。 您知道如何使用ajv进行验证吗?
PS:作为一种替代解决方案,我当然可以使用以下结构:
const dataStructure = {
mobiles: [{
id: xxx1234,
mobile: "ios"
}, {
id: yyy89B,
mobile: "android"
}]
};
然后,我将不得不在数组上循环查找所需的ID。 我所有的查询都会变得更加复杂,这使我感到困扰。
谢谢您的帮助!
答案 0 :(得分:1)
下面的示例可能会对您有所帮助。
1. 验证动态键值
根据您的要求更新正则表达式。
const dataStructure = {
11: { mobile: "android" },
86: { mobile: "android" }
};
var schema2 = {
"type": "object",
"patternProperties": {
"^[0-9]{2,6}$": { //allow key only `integer` and length between 2 to 6
"type": "object"
}
},
"additionalProperties": false
};
var validate = ajv.compile(schema2);
console.log(validate(dataStructure)); // true
console.log(dataStructure);
2. 使用简单数据类型验证JSON数组。
var schema = {
"properties": {
"mobiles": {
"type": "array", "items": {
"type": "object", "properties": {
"id": { "type": "string" },
"mobile": { "type": "string" }
}
}
}
}
};
const data = {
mobiles: [{
id: 'xxx1234',
mobile: "ios"
}]
};
var validate = ajv.compile(schema);
console.log(validate(data)); // true
console.log(data);
您可以根据要求添加验证。