Last active
May 26, 2022 11:50
-
-
Save Avi-E-Koenig/9774f231e20e8e0de27de09e8f0b45de to your computer and use it in GitHub Desktop.
draft concept to validate json structure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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