Skip to content

Instantly share code, notes, and snippets.

@Avi-E-Koenig
Last active May 26, 2022 11:50
Show Gist options
  • Save Avi-E-Koenig/9774f231e20e8e0de27de09e8f0b45de to your computer and use it in GitHub Desktop.
Save Avi-E-Koenig/9774f231e20e8e0de27de09e8f0b45de to your computer and use it in GitHub Desktop.
draft concept to validate json structure
const validateSchema = (json, schema) => {
try {
JSON.parse(json)
const parsed = JSON.parse(json)
for (const key in parsed) {
if (!schema.hasOwnProperty(key)) {
return false;
}
if (typeof parsed[key] !== schema[key]) {
return false;
}
if (parsed[key] === null) {
continue;
}
if (parsed[key] !== null && typeof parsed[key] === 'object') {
validateSchema(JSON.stringify(parsed[key]), schema[key])
}
if (parsed[key] !== null && Array.isArray(yourVariable)) {
parsed[key].forEach(subItem => {
validateSchema(JSON.stringify(parsed[key]), schema[key])
});
}
}
return true;
} catch (error) {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment