代码之家  ›  专栏  ›  技术社区  ›  CCCC

nodejs-嵌套JSON对象的JSON验证程序

  •  -1
  • CCCC  · 技术社区  · 5 年前

    这是理想的格式。

    {
        "sectionId": 1,
        "sub_sections": [
            {
                "subSectionId": 1,
                "questions": [
                    {
                        "questionId": 1,
                        "answerId": 4
                    },
                    {
                        "questionId": 2,
                        "answerId": 4
                    },
                    {
                        "questionId": 3,
                        "answerId": 4
                    }
                ]
            }
        ]
    }
    

    sub_sections 和 questions

    我找到了一些像这样的图书馆 ajv ,但它似乎无法处理嵌套的JSON。

    1 回复  |  直到 5 年前
        1
  •  2
  •   Petr Hejda    5 年前

    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
    
    推荐文章