Security News
PyPI Introduces Digital Attestations to Strengthen Python Package Security
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
The z-schema npm package is a JSON Schema validator that is compliant with the latest JSON Schema standards. It allows users to validate JSON data against a schema to ensure it meets certain criteria before processing it. This can be particularly useful for validating configuration files, API request payloads, and any other JSON data that requires validation against a predefined structure.
Validation of JSON data
This feature allows you to validate JSON data against a JSON Schema. The code sample demonstrates how to create a new ZSchema validator instance, define a schema, and validate data against that schema.
{"var ZSchema = require('z-schema');
var validator = new ZSchema();
var schema = {"type": "object","properties": {"name": {"type": "string"}}};
var data = {"name": "John Doe"};
validator.validate(data, schema, function(err, valid) {console.log(valid);});}
Custom format validators
Z-schema allows you to define custom formats for data validation. In this code sample, a custom format called 'custom-format' is defined and used in a schema to validate a string.
{"var ZSchema = require('z-schema');
var validator = new ZSchema();
validator.setFormat('custom-format', function(str) {return str === 'custom';});
var schema = {"type": "string","format": "custom-format"};
var data = 'custom';
validator.validate(data, schema, function(err, valid) {console.log(valid);});}
Asynchronous validation
Z-schema supports asynchronous validation using promises. This code sample shows how to validate data against a schema asynchronously.
{"var ZSchema = require('z-schema');
var validator = new ZSchema();
var schema = {"type": "object","properties": {"name": {"type": "string"}}};
var data = {"name": "John Doe"};
validator.validate(data, schema).then(function(valid) {console.log(valid);}).catch(function(err) {console.error(err);});}
Remote references
Z-schema can handle remote references in schemas. This code sample demonstrates how to set up a validator with a remote reference and validate data against it.
{"var ZSchema = require('z-schema');
var validator = new ZSchema({remoteReferences: {"http://my.site/myschema.json": {"type": "object"}}});
var schema = {"$ref": "http://my.site/myschema.json"};
var data = {"name": "John Doe"};
validator.validate(data, schema, function(err, valid) {console.log(valid);});}
Ajv is a fast JSON Schema validator that supports draft-06/07/2019-09 JSON Schema standards. It is known for its performance and is often used in projects that require high-speed validation. Compared to z-schema, Ajv may offer better performance and more up-to-date standards support.
Tiny Validator (tv4) is a small and fast JSON Schema validator that supports draft-04 of the JSON Schema. It is simpler and has a smaller footprint than z-schema, making it suitable for environments with limited resources or where a simple validation solution is needed.
The jsonschema package is another validator for JSON Schema that supports various schema versions. It is designed to be easy to use and extend, with a straightforward API. While z-schema is focused on compliance with the standards, jsonschema emphasizes ease of use and extensibility.
JSON Schema validator for Node.js (draft4 version)
Coded according to:
json-schema documentation, json-schema-core, json-schema-validation, json-schema-hypermedia
Passing all tests here (even optional, except zeroTerminatedFloats and some URI tests, see more info in #18):
json-schema/JSON-Schema-Test-Suite
Will try to maintain this as much as possible, all bug reports welcome.
If you need to automatize validation of your schemas, there's a Grunt plugin grunt-z-schema by Petr Bela
rawgithub.com/zaggino/z-schema/master/benchmark/results.html
var ZSchema = require("z-schema");
ZSchema.validate(json, schema)
.then(function(report){
// successful validation
// there might be warnings: console.log(report.warnings)
})
.catch(function(err){
console.error(err.errors)
})
There is also support for sync mode like this:
var validator = new ZSchema({ sync: true });
var valid = validator.validate(json, schema);
if (!valid) {
var error = validator.getLastError();
}
Using traditional callback:
ZSchema.validate(json, schema, function(err, report){
if(err){
console.error(err.errors);
return;
}
// successful validation
// there might be warnings: console.log(report.warnings)
})
If you need just to validate your schema, you can do it like this:
var validator = new ZSchema();
validator.validateSchema(schema)
.then(function(report){
})
.catch(function(err){
})
Or with Node.js style callback:
var validator = new ZSchema();
validator.validateSchema(schema, function (err, report) {
if (err) ...
});
Your schemas can include remote references that should be real URIs (more on that here) so validator can make a request and download the schema needed. Validator automatically caches these remote requests so they are not repeated with every validation.
In case you don't have a real server or you'd like to load files from different location, you can preload remote locations into the validator like this:
var fileContent = fs.readFileSync(__dirname + '/../json_schema_test_suite/remotes/integer.json', 'utf8');
ZSchema.setRemoteReference('http://localhost:1234/integer.json', fileContent);
http://localhost:1234/integer.json
doesn't have to be online now, all schemas
referencing it will validate against string
that was passed to the function.
You can pre-compile schemas (for example on your server startup) so your application is not bothered by schema compilation and validation when validating ingoing / outgoing objects.
Promises:
var validator = new ZSchema();
validator.compileSchema(schema)
.then(function(compiledSchema){
})
Or callback:
var validator = new ZSchema();
validator.compileSchema(schema, function (err, compiledSchema) {
assert.isUndefined(err);
...
});
Then you can re-use compiled schemas easily just the same way as non-compiled.
var validator = new ZSchema();
validator.validate(json, compiledSchema)
.then(function(report){
// ...
})
.catch(function(err){
console.error(err.errors)
})
You can add validation for your own custom string formats like this: (these are added to all validator instances, because it would never make sense to have multiple functions to validate format with the same name)
var validator = new ZSchema();
ZSchema.registerFormat('xstring', function (str) {
return str === 'xxx'; // return true/false as a result of validation
});
validator.validate('xxx', {
'type': 'string',
'format': 'xstring'
})
.then(function(){})
.catch(function(err){})
Custom validators can also be async:
Using promises:
ZSchema.registerFormat('xstring', function (str) {
return Q.delay(1000).thenResolve(return str === 'xxx'); // return a promise for validation result
});
Using classic callback:
ZSchema.registerFormat('xstring', function (str, callback) {
setTimeout(function(){
callback(null, str === 'xxx');
// or return custom error: callback(new Error('Bad, bad value!'))
}, 2000)
});
Any exception thrown (or returned via classic callback) in custom validation function is written into validation error:
ZSchema.registerFormat('xstring', function (str) {
throw new Error('Bad, bad value!');
});
And then expect errors to contain something like this:
[{ code: 'FORMAT',
message: 'xstring format validation failed: Error: Bad, bad value!',
path: '#/test',
params: { format: 'xstring', error: [Error: Bad, bad value!] } } ]
When creating new instance of validator, you can specify some options that will alter the validator behaviour like this:
var validator = new ZSchema({
option: true
});
true/false
when true, do not allow unknown keywords in schema
true/false
when true, always adds minLength: 1 to schemas where type is string
true/false
when true, every schema must specify a type
true/false
when true, forces not to leave out some keys on schemas (additionalProperties, additionalItems)
true/false
when true, forces not to leave out properties or patternProperties on type-object schemas
true/false
when true, forces not to leave out items on array-type schemas
true/false
when true, forces not to leave out maxLength on string-type schemas, when format or enum is not specified
Alternatively, you can turn on all of the above options with:
var validator = new ZSchema({
strict: true
});
true/false
when true, disables caching of compiled schemas - cache is used to resolve references to other schemas by their ID
true/false
when true, uri's need to be in full rfc3986 format, by default checks for uri-fragment, more info in #18
Avoid JSHint errors - settings for the JSHint are specified in .jshintrc
.
You can check for errors using grunt
command which runs both jshint and mocha tests.
Please check for errors before opening any pull requests.
FAQs
JSON schema validator
The npm package z-schema receives a total of 902,179 weekly downloads. As such, z-schema popularity was classified as popular.
We found that z-schema demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer 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
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
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.