tv4

2020-04-24  本文已影响0人  antlove

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' 
    } 
]
上一篇下一篇

猜你喜欢

热点阅读