tv4

作者: antlove | 来源:发表于2020-04-24 14:42 被阅读0次

    https://github.com/geraintluff/tv4

    output.json
    {
        "type": "object",
        "properties": {
            "shape": {
                "$ref": "#/definitions/Shape"
            },
            "point": {
                "$ref": "#/definitions/XY"
            },
            "radius": {
                "type": "number"
            }
        },
        "required": [
            "point",
            "radius",
            "shape"
        ],
        "definitions": {
            "Shape": {
                "type": "object",
                "properties": {
                    "size": {
                        "type": "number"
                    }
                },
                "required": [
                    "size"
                ]
            },
            "XY": {
                "type": "object",
                "properties": {
                    "x": {
                        "type": "number"
                    },
                    "y": {
                        "type": "number"
                    }
                },
                "required": [
                    "x",
                    "y"
                ]
            }
        },
        "$schema": "http://json-schema.org/draft-07/schema#"
    }
    
    main.js
    const fs = require('fs');
    const tv4 = require('tv4');
    const content = fs.readFileSync('output.json', {encoding: 'utf8'});
    const schema = JSON.parse(content);
    const data = {
        shape: {size: 10},
        point: {x:0, y: ''},
        radius: 1,
    };
    const ret = tv4.validateMultiple(data, schema);
    
    const errRet = formatErrorMsg(ret.errors);
    console.log(errRet);
    
    function formatErrorMsg(errs) {
        return errs.map(e => {
            return {
                msg: e.message,
                attr: 'obj' + e.dataPath.replace(/\//g,'.'),
            };
        });
    }
    
    结构
    [ 
        { 
            msg: 'Invalid type: string (expected number)',
            attr: 'obj.point.y' 
        } 
    ]
    

    相关文章

      网友评论

          本文标题:tv4

          本文链接:https://www.haomeiwen.com/subject/dbrfwhtx.html