Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
is-my-json-valid
Advanced tools
A [JSONSchema](https://json-schema.org/) validator that uses code generation to be extremely fast.
The is-my-json-valid npm package is a JSON schema validator that is fast and simple to use. It allows you to validate JSON data against a schema, ensuring that the data conforms to the expected structure and types.
Basic JSON Validation
This feature allows you to validate a simple JSON object against a schema. In this example, the schema expects an object with a string 'name' and a number 'age'. The provided JSON object meets these criteria, so the validation returns true.
const validator = require('is-my-json-valid');
const validate = validator({ type: 'object', properties: { name: { type: 'string' }, age: { type: 'number' } } });
const valid = validate({ name: 'John', age: 30 });
console.log(valid); // true
Custom Error Messages
This feature provides detailed error messages when validation fails. In this example, the 'age' property is a string instead of a number, so the validation fails and the errors are logged.
const validator = require('is-my-json-valid');
const validate = validator({ type: 'object', properties: { name: { type: 'string' }, age: { type: 'number' } } }, { verbose: true });
const valid = validate({ name: 'John', age: 'thirty' });
if (!valid) console.log(validate.errors);
Formats and Custom Formats
This feature allows you to use predefined formats like 'email' to validate specific types of strings. In this example, the 'email' property must be a valid email address.
const validator = require('is-my-json-valid');
const validate = validator({ type: 'object', properties: { email: { type: 'string', format: 'email' } } });
const valid = validate({ email: 'test@example.com' });
console.log(valid); // true
AJV (Another JSON Schema Validator) is a highly efficient and feature-rich JSON schema validator. It supports JSON Schema draft-07 and provides advanced features like asynchronous validation, custom keywords, and more. Compared to is-my-json-valid, AJV offers more extensive support for JSON Schema specifications and additional features.
The jsonschema package is a simple and easy-to-use JSON schema validator. It supports JSON Schema draft-04 and is suitable for basic validation needs. While it may not be as fast as is-my-json-valid, it provides a straightforward API for validating JSON data.
Joi is a powerful schema description language and data validator for JavaScript objects. It allows you to define schemas using a fluent API and provides extensive validation capabilities. Unlike is-my-json-valid, Joi is not limited to JSON Schema and offers more flexibility in defining and validating data structures.
A JSONSchema validator that uses code generation to be extremely fast.
It passes the entire JSONSchema v4 test suite except for remoteRefs
and maxLength
/minLength
when using unicode surrogate pairs.
npm install --save is-my-json-valid
Simply 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 __dirname
var validator = require('is-my-json-valid/require')
var validate = validator('my-schema.json')
is-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
You can pass in external schemas that you reference using the $ref
attribute as the schemas
option
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
is-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'}
When the verbose
options is set to true
, is-my-json-valid
also outputs:
value
: The data value that caused the errorschemaPath
: an array of keys indicating which sub-schema failedvar 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 schemaPath
:
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
By 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'}]
Here is a list of possible message
values for errors:
is required
is the wrong type
has additional items
must be FORMAT format
(FORMAT is the format
property from the schema)must be unique
must be an enum value
dependencies not set
has additional properties
referenced schema does not match
negative schema matches
pattern mismatch
no schemas match
no (or more than one) schemas match
has a remainder
has more properties than allowed
has less properties than allowed
has more items than allowed
has less items than allowed
has longer length than allowed
has less length than allowed
is less than minimum
is more than maximum
is-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.
This 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 unknown
and thus require TypeScript 3.0 or later.
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.
MIT
FAQs
A [JSONSchema](https://json-schema.org/) validator that uses code generation to be extremely fast.
The npm package is-my-json-valid receives a total of 342,777 weekly downloads. As such, is-my-json-valid popularity was classified as popular.
We found that is-my-json-valid demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 7 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.