Skip to content

Instantly share code, notes, and snippets.

@peter
Created October 6, 2021 09:17
Show Gist options
  • Select an option

  • Save peter/24eae0a74619b1dfa594dac8fa207c3c to your computer and use it in GitHub Desktop.

Select an option

Save peter/24eae0a74619b1dfa594dac8fa207c3c to your computer and use it in GitHub Desktop.

Revisions

  1. peter created this gist Oct 6, 2021.
    51 changes: 51 additions & 0 deletions to-json-schema.js
    Original 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()