在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:mafintosh/is-my-json-valid开源软件地址:https://github.com/mafintosh/is-my-json-valid开源编程语言:JavaScript 77.3%开源软件介绍:is-my-json-validA JSONSchema validator that uses code generation to be extremely fast. It passes the entire JSONSchema v4 test suite except for Installationnpm install --save is-my-json-valid UsageSimply pass a schema to compile it var validator = require('is-my-json-valid')
var validate = validator({
required: true,
type: 'object',
properties: {
hello: {
required: true,
type: 'string'
}
}
})
console.log('should be valid', validate({hello: 'world'}))
console.log('should not be valid', validate({}))
// get the last list of errors by checking validate.errors
// the following will print [{field: 'data.hello', message: 'is required'}]
console.log(validate.errors) You can also pass the schema as a string var validate = validator('{"type": ... }') Optionally you can use the require submodule to load a schema from var validator = require('is-my-json-valid/require')
var validate = validator('my-schema.json') Custom formatsis-my-json-valid supports the formats specified in JSON schema v4 (such as date-time). If you want to add your own custom formats pass them as the formats options to the validator var validate = validator({
type: 'string',
required: true,
format: 'only-a'
}, {
formats: {
'only-a': /^a+$/
}
})
console.log(validate('aa')) // true
console.log(validate('ab')) // false External schemasYou can pass in external schemas that you reference using the var ext = {
required: true,
type: 'string'
}
var schema = {
$ref: '#ext' // references another schema called ext
}
// pass the external schemas as an option
var validate = validator(schema, {schemas: {ext: ext}})
validate('hello') // returns true
validate(42) // return false Filtering away additional propertiesis-my-json-valid supports filtering away properties not in the schema var filter = validator.filter({
required: true,
type: 'object',
properties: {
hello: {type: 'string', required: true}
},
additionalProperties: false
})
var doc = {hello: 'world', notInSchema: true}
console.log(filter(doc)) // {hello: 'world'} Verbose mode shows more information about the source of the errorWhen the
var schema = {
required: true,
type: 'object',
properties: {
hello: {
required: true,
type: 'string'
}
}
}
var validate = validator(schema, {
verbose: true
})
validate({hello: 100});
console.log(validate.errors)
// [ { field: 'data.hello',
// message: 'is the wrong type',
// value: 100,
// type: 'string',
// schemaPath: [ 'properties', 'hello' ] } ] Many popular libraries make it easy to retrieve the failing rule with the var schemaPath = validate.errors[0].schemaPath
var R = require('ramda')
console.log( 'All evaluate to the same thing: ', R.equals(
schema.properties.hello,
{ required: true, type: 'string' },
R.path(schemaPath, schema),
require('lodash').get(schema, schemaPath),
require('jsonpointer').get(schema, [""].concat(schemaPath))
))
// All evaluate to the same thing: true Greedy mode tries to validate as much as possibleBy default is-my-json-valid bails on first validation error but when greedy is set to true it tries to validate as much as possible: var validate = validator({
type: 'object',
properties: {
x: {
type: 'number'
}
},
required: ['x', 'y']
}, {
greedy: true
});
validate({x: 'string'});
console.log(validate.errors) // [{field: 'data.y', message: 'is required'},
// {field: 'data.x', message: 'is the wrong type'}] Error messagesHere is a list of possible
Performanceis-my-json-valid uses code generation to turn your JSON schema into basic javascript code that is easily optimizeable by v8. At the time of writing, is-my-json-valid is the fastest validator when running If you know any other relevant benchmarks open a PR and I'll add them. TypeScript supportThis library ships with TypeScript typings. They are still early on and not perfect at the moment, but should hopefully handle the most common cases. If you find anything that doesn't work, please open an issue and we'll try to solve it. The typings are using Here is a quick sample of usage together with express: import createError = require('http-errors')
import createValidator = require('is-my-json-valid')
import { Request, Response, NextFunction } from 'express'
const personValidator = createValidator({
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' },
},
required: [
'name'
]
})
export function post (req: Request, res: Response, next: NextFunction) {
// Here req.body is typed as: any
if (!personValidator(req.body)) {
throw createError(400, { errors: personValidator.errors })
}
// Here req.body is typed as: { name: string, age: number | undefined }
} As you can see, the typings for is-my-json-valid will contruct an interface from the schema passed in. This allows you to work with your incoming json body in a type safe way. LicenseMIT |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论