Skip to content

Instantly share code, notes, and snippets.

@peter
Created October 1, 2021 13:06
Show Gist options
  • Save peter/7a182d4107234bcd9052e26dd3f8c79f to your computer and use it in GitHub Desktop.
Save peter/7a182d4107234bcd9052e26dd3f8c79f to your computer and use it in GitHub Desktop.
JSON to JSON Schema Script
#!/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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment