Created
October 6, 2021 09:17
-
-
Save peter/24eae0a74619b1dfa594dac8fa207c3c to your computer and use it in GitHub Desktop.
Revisions
-
peter created this gist
Oct 6, 2021 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,51 @@ #!/usr/bin/env node const fs = require('fs') // NOTE: this package didn't work for me // const toJsonSchema = require('to-json-schema') var stringify = require('json-stable-stringify') const Ajv = require('ajv') const ajv = new Ajv() function isObject (value) { return value != null && typeof value === 'object' && value.constructor === Object } function toSchema(data) { if (isObject(data)) { return { type: 'object', properties: Object.keys(data).reduce((properties, key) => { properties[key] = toSchema(data[key]) return properties }, {}) } } else if (Array.isArray(data)) { return { type: 'array', items: toSchema(data[0]) } } else { return { type: (typeof data) } } } async function main() { const data = JSON.parse(fs.readFileSync(0)) const schema = toSchema(data) const isValidSchema = ajv.validateSchema(schema) if (!isValidSchema) { console.log('WARNING! schema is not valid!') } const validate = ajv.compile(schema) const valid = validate(data) if (!valid) { console.log('WARNING! schema errors:', stringify(validate.errors, { space: 2})) } console.log(stringify(schema, { space: 2 })) } main()