admin管理员组文章数量:1333177
I use ajv to validate JSON data model before inserting/updating my database.
Today I want to use this structure:
const dataStructure = {
xxx1234: { mobile: "ios" },
yyy89B: { mobile: "android" }
};
My keys are dynamic because they are ids. Do you know how to validate it with ajv ?
PS: as an alternative solution, i can of course use this structure:
const dataStructure = {
mobiles: [{
id: xxx1234,
mobile: "ios"
}, {
id: yyy89B,
mobile: "android"
}]
};
Then I would have to loop on the array to find the ids I want. All my queries will bee more plex, it bothers me.
Thank you for your help !
I use ajv to validate JSON data model before inserting/updating my database.
Today I want to use this structure:
const dataStructure = {
xxx1234: { mobile: "ios" },
yyy89B: { mobile: "android" }
};
My keys are dynamic because they are ids. Do you know how to validate it with ajv ?
PS: as an alternative solution, i can of course use this structure:
const dataStructure = {
mobiles: [{
id: xxx1234,
mobile: "ios"
}, {
id: yyy89B,
mobile: "android"
}]
};
Then I would have to loop on the array to find the ids I want. All my queries will bee more plex, it bothers me.
Thank you for your help !
Share Improve this question asked Oct 30, 2018 at 8:57 Vivien AdnotVivien Adnot 1,2574 gold badges17 silver badges31 bronze badges1 Answer
Reset to default 8Below example may help you.
1.Validate dynamic key value
Update regex with your requirement.
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.pile(schema2);
console.log(validate(dataStructure)); // true
console.log(dataStructure);
2.Validate array of JSON with simple data types.
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.pile(schema);
console.log(validate(data)); // true
console.log(data);
You can add your validation as per requirement.
本文标签: javascriptAjv validate json with dynamic keysStack Overflow
版权声明:本文标题:javascript - Ajv: validate json with dynamic keys - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742285085a2446785.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论