Skip to content

Instantly share code, notes, and snippets.

@jaylandro
Created March 14, 2021 00:26
Show Gist options
  • Save jaylandro/0a205a5d4865c1329c16022b1f0e5776 to your computer and use it in GitHub Desktop.
Save jaylandro/0a205a5d4865c1329c16022b1f0e5776 to your computer and use it in GitHub Desktop.
JSON Schema Validatior
const rootSchema = {
$schema: "http://json-schema.org/draft-04/schema#",
title: "Person",
description: "A person",
type: "object",
properties: {
name: {
description: "A person's name",
type: "string",
},
age: {
description: "A person's age",
type: "number",
minimum: 18,
maximum: 64,
},
location: {
description: "Geo-coordinates of a person",
type: "object",
},
friends: {
description: "People should have some friends",
type: "array:person",
},
},
required: ["name", "age"],
};
const person = {
name: "Jay",
age: 77,
friends: ["ewq", "cds"],
location: {},
// bob: true,
};
function validate(schema, model) {
const schemaKeys = [...Object.keys(schema.properties)];
const modelKeys = [...Object.keys(model)];
for (let requiredField of schema.required) {
if (!model[requiredField]) {
return `Missing required property ${requiredField}`;
}
}
const unexpectedProperties = modelKeys.filter(
(key) => !schemaKeys.includes(key)
);
if (unexpectedProperties.length > 0) {
return `Error, unexpected property ${unexpectedProperties} is not allowed based on schema`;
}
for (let key of schemaKeys) {
if (model[key] === undefined) {
continue;
}
const schemaType = schema.properties[key].type;
const modelType = Array.isArray(model[key]) ? "array" : typeof model[key];
if (!schemaType.includes(modelType)) {
return `Error, property ${key} is expected to be of type ${schemaType}`;
}
}
return `Your model is valid based on the schema, hurray!`;
}
console.log("|----------------------------->\n");
console.log(validate(rootSchema, person), "\n");
console.log("|----------------------------->\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment