Skip to content

Instantly share code, notes, and snippets.

@nmarley
Last active February 8, 2023 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmarley/aa77faded988622f15075f8d1d8eb733 to your computer and use it in GitHub Desktop.
Save nmarley/aa77faded988622f15075f8d1d8eb733 to your computer and use it in GitHub Desktop.
JSON Schema validation example in Node.JS
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "InventoryItem",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"price": {
"type": "number",
"minimum": 0
},
"sku": {
"description": "Stock Keeping Unit",
"type": "integer"
}
},
"required": ["name", "price"]
}
var Validator = require('jsonschema').Validator;
var v = new Validator();
var schema = require('./schema-example.json');
var object;
object = {name: "eggs", price: 21.47};
console.log(v.validate(object, schema));
console.log("========================================================================");
object = 4;
console.log(v.validate(object, schema));
@shamoon1997
Copy link

Hey man how can i check that data is validated correctly or data is in correct format whether it returns true or false ???

@DcsPeterDickten
Copy link

Hey man how can i check that data is validated correctly or data is in correct format whether it returns true or false ???

const res = v.validate(object, schema);
console.log(res.errors.length > 0);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment