ajv
使用
JSON schema
标准,它能够处理嵌套的json。JSON模式是OpenAPI标准的一部分(
official
docs
大摇大摆地)。
const Ajv = require("ajv");
const ajv = new Ajv();
const input = {
"sectionId": 1,
"sub_sections": [
{
"subSectionId": 1,
"questions": [
{
"questionId": 1,
"answerId": 4
},
{
"questionId": 2,
"answerId": 4
},
{
"questionId": 3,
"answerId": 4
}
]
}
]
};
const schema = {
type: 'object',
properties: {
sectionId: {type: 'integer'},
sub_sections: {
type: 'array',
items: {
type: 'object',
properties: {
subSectionId: {type: 'integer'},
questions: {
type: 'array',
items: {
type: 'object',
properties: {
questionId: {type: 'integer'},
answerId: {type: 'integer'}
},
required: ['questionId', 'answerId'],
additionalProperties: false
}
}
},
required: ['subSectionId', 'questions'],
additionalProperties: false
}
}
},
required: ['sectionId', 'sub_sections'],
additionalProperties: false
};
const validate = ajv.compile(schema);
const valid = validate(input);
console.log(valid); // prints true