Skip to content

Instantly share code, notes, and snippets.

@simonespa
Created August 10, 2020 16:54
Show Gist options
  • Select an option

  • Save simonespa/6c49a679af5aee104dece3c0c12b393a to your computer and use it in GitHub Desktop.

Select an option

Save simonespa/6c49a679af5aee104dece3c0c12b393a to your computer and use it in GitHub Desktop.
JSON schema validation
const Validator = require('jsonschema').Validator;
const v = new Validator();
// Address, to be embedded on Person
const addressSchema = {
id: '/SimpleAddress',
type: 'object',
properties: {
lines: {
type: 'array',
items: { type: 'string' },
},
zip: { type: 'string' },
city: { type: 'string' },
country: { type: 'string' },
},
required: ['country'],
};
// Person
const schema = {
id: '/SimplePerson',
type: 'object',
properties: {
name: { type: 'string' },
address: { $ref: '/SimpleAddress' },
votes: { type: 'integer', minimum: 1 },
},
};
const p = {
name: 'Barack Obama',
address: {
lines: ['1600 Pennsylvania Avenue Northwest'],
zip: 'DC 20500',
city: 'Washington',
country: 'USA',
},
votes: 3,
};
v.addSchema(addressSchema, '/SimpleAddress');
console.log(v.validate(p, schema));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment