Research
Security News
Malicious npm Package Targets Solana Developers and Hijacks Funds
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
chai-json-schema
Advanced tools
The chai-json-schema npm package is a Chai plugin that provides assertions for validating JSON objects against JSON schemas. It allows you to write tests that ensure your JSON data conforms to a specified schema, making it easier to validate the structure and content of JSON responses in your tests.
Basic Schema Validation
This feature allows you to validate a JSON object against a defined schema. In this example, the `validPerson` object is validated against the `schema` to ensure it has the required properties and types.
const chai = require('chai');
const chaiJsonSchema = require('chai-json-schema');
chai.use(chaiJsonSchema);
const expect = chai.expect;
const schema = {
title: 'Person',
type: 'object',
required: ['name', 'age'],
properties: {
name: {
type: 'string'
},
age: {
type: 'integer'
}
}
};
const validPerson = {
name: 'John Doe',
age: 30
};
expect(validPerson).to.be.jsonSchema(schema);
Nested Schema Validation
This feature allows you to validate JSON objects with nested schemas. In this example, the `validPerson` object includes an `address` property that is validated against the `addressSchema`.
const chai = require('chai');
const chaiJsonSchema = require('chai-json-schema');
chai.use(chaiJsonSchema);
const expect = chai.expect;
const addressSchema = {
title: 'Address',
type: 'object',
required: ['street', 'city'],
properties: {
street: {
type: 'string'
},
city: {
type: 'string'
}
}
};
const personSchema = {
title: 'Person',
type: 'object',
required: ['name', 'age', 'address'],
properties: {
name: {
type: 'string'
},
age: {
type: 'integer'
},
address: {
$ref: 'addressSchema'
}
}
};
const validPerson = {
name: 'John Doe',
age: 30,
address: {
street: '123 Main St',
city: 'Anytown'
}
};
chai.tv4.addSchema('addressSchema', addressSchema);
expect(validPerson).to.be.jsonSchema(personSchema);
Array Schema Validation
This feature allows you to validate arrays of JSON objects against a schema. In this example, the `validPeople` array is validated to ensure each object in the array conforms to the `personSchema`.
const chai = require('chai');
const chaiJsonSchema = require('chai-json-schema');
chai.use(chaiJsonSchema);
const expect = chai.expect;
const personSchema = {
title: 'Person',
type: 'object',
required: ['name', 'age'],
properties: {
name: {
type: 'string'
},
age: {
type: 'integer'
}
}
};
const peopleSchema = {
title: 'People',
type: 'array',
items: personSchema
};
const validPeople = [
{ name: 'John Doe', age: 30 },
{ name: 'Jane Doe', age: 25 }
];
expect(validPeople).to.be.jsonSchema(peopleSchema);
Ajv is a JSON schema validator that is highly performant and supports JSON Schema draft-07 and later. It is more feature-rich compared to chai-json-schema and can be used independently of any testing framework. Ajv also supports custom keywords and formats, making it highly extensible.
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. Compared to chai-json-schema, jsonschema is more focused on validation and does not integrate directly with testing frameworks like Chai.
Joi is a powerful schema description language and data validator for JavaScript objects. It is not limited to JSON and can validate any JavaScript object. Joi is more versatile and feature-rich compared to chai-json-schema, offering a wide range of validation options and customizations.
Chai plugin with assertions to validate values against JSON Schema v4.
Assert both simple values and complex objects with the rich collection of validation terms (examples).
For general help with json-schema see this excellent guide and usable reference.
JSON Schema validation is done by Tiny Validator tv4.
It seems that tv4 is not actively developed anymore, nor does it support versions of JSON schema after draft-04. However this chai plugin will use tv4 as its backend for the forseeable future. If you want newer versions of the JSON-schema or more performance you could look at using ajv in conjunction with chai-json-schema-ajv
The assertion will fail if a schema use a $ref
to a schema that is not added before the assertion is called. Use chai.tv4.addSchema(uri, schema)
to preset schemas.
JSON Schema's main use-case is validating JSON documents and API responses, but it is also a powerful way to describe and validate any JavaScript value or object.
Install from npm:
$ npm install chai-json-schema
Have chai use the chai-json-schema module:
var chai = require('chai');
chai.use(require('chai-json-schema'));
Using globals:
Include chai-json-schema after jsonpointer.js, Tiny Validator tv4 and Chai:
<script src="jsonpointer.js"></script>
<script src="tv4.js"></script>
<script src="chai.js"></script>
<script src="chai-json-schema.js"></script>
Install from bower:
$ bower install chai-json-schema
The module supports CommonJS, AMD and browser globals. You might need to shim tv4
's global and make sure jsonpointer.js
can be required as 'jsonpointer'
.
Validate that the given javascript value conforms to the specified JSON Schema. Both the value and schema would likely be JSON loaded from an external datasource but could also be literals or object instances.
var goodApple = {
skin: 'thin',
colors: ['red', 'green', 'yellow'],
taste: 10
};
var badApple = {
colors: ['brown'],
taste: 0,
worms: 2
};
var fruitSchema = {
title: 'fresh fruit schema v1',
type: 'object',
required: ['skin', 'colors', 'taste'],
properties: {
colors: {
type: 'array',
minItems: 1,
uniqueItems: true,
items: {
type: 'string'
}
},
skin: {
type: 'string'
},
taste: {
type: 'number',
minimum: 5
}
}
};
//bdd style
expect(goodApple).to.be.jsonSchema(fruitSchema);
expect(badApple).to.not.be.jsonSchema(fruitSchema);
goodApple.should.be.jsonSchema(fruitSchema);
badApple.should.not.be.jsonSchema(fruitSchema);
//tdd style
assert.jsonSchema(goodApple, fruitSchema);
assert.notJsonSchema(badApple, fruitSchema);
The tv4
instance is 'exported' as chai.tv4
and can be accessed to add schemas for use in validations:
chai.tv4.addSchema(uri, schema);
There are other useful methods:
var list = chai.tv4.getMissingUris();
var list = chai.tv4.getMissingUris(/^https?:/);
var list = chai.tv4.getSchemaUris();
var list = chai.tv4.getSchemaUris(/example.com/);
var schema = chai.tv4.getSchema('http://example.com/item');
var schema = chai.tv4.getSchema('http://example.com/item/#sub/type');
chai.tv4.dropSchemas();
For more API methods and info on the validator see the tv4 documentation.
Cyclical objects
This will be passed to the internal tv4
validate call to enable support for cyclical objects. It allows tv4 to validate normal javascipt structures (instead of pure JSON) without risk of entering a loop on cyclical references.
chai.tv4.cyclicCheck = true;
This is slightly slower then regular validation so it is disabled by default.
Ban unknown properties
chai.tv4.banUnknown = true;
Passed to the internal tv4
validate call makes validation fail on unknown schema properties. Use this to make sure your schema do not contain undesirable data.
Validate multiple errors
chai.tv4.multiple = true;
Call tv4.validateMultiple
for validation instead of tv4.validateResult
. Use this if you want see all validation errors.
Due to the synchronous nature of assertions there will be no support for dynamically loading remote references during validation.
Use the asynchronous preparation feature of your favourite test runner to preload remote schemas:
// simplified example using a bdd-style async before();
// as used in mocha, jasmine etc.
before(function (done) {
// iterate missing
var checkMissing = function (callback) {
var missing = chai.tv4.getMissingUris();
if (missing.length === 0) {
// all $ref's solved
callback();
return;
}
// load a schema using your favourite JSON loader
// (jQuery, request, SuperAgent etc)
var uri = missing.pop();
myFavoriteJsonLoader.load(uri, function (err, schema) {
if (err || !schema) {
callback(err || 'no data loaded');
return;
}
// add it
chai.tv4.addSchema(uri, schema);
// iterate
checkMissing(callback);
});
};
// load first instance manually
myFavoriteJsonLoader.load(uri, function (err, schema) {
if (err || !schema) {
done(err || 'no data loaded');
return;
}
// add it
chai.tv4.addSchema(uri, schema);
// start checking
checkMissing(done);
});
});
See Releases.
Install development dependencies in your git checkout:
$ npm install
You need the global grunt command:
$ npm install grunt-cli -g
Build and run tests:
$ grunt
See the Gruntfile
for additional commands.
Copyright (c) 2013 Bart van der Schoor
Licensed under the MIT license.
FAQs
Chai plugin for JSON Schema v4
The npm package chai-json-schema receives a total of 183,694 weekly downloads. As such, chai-json-schema popularity was classified as popular.
We found that chai-json-schema demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 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.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.