Created
November 20, 2021 23:16
-
-
Save maxpatiiuk/d4ef9186113913cfe5a8732834645144 to your computer and use it in GitHub Desktop.
Basic inference of JSON Schema from a JSON object
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 c = require('/usr/local/lib/node_modules/clipboardy'); | |
const resolve = (value) => | |
Array.isArray(value) | |
? { type: 'array', items: resolve(value[0]) } | |
: typeof value === 'object' | |
? { | |
type: 'object', | |
properties: Object.fromEntries( | |
Object.entries(value).map(([key, value]) => [key, resolve(value)]) | |
), | |
} | |
: { type: typeof value, example: value }; | |
const defaultOffset = ' '; | |
const format = (value, offset = '') => | |
`${Object.entries(value) | |
.map( | |
([key, value]) => | |
`${offset}${key}:${ | |
typeof value === 'object' | |
? `\n${format(value, `${offset}${defaultOffset}`)}` | |
: ` ${value}` | |
}` | |
) | |
.join('\n')}`; | |
// Takes source from clipboard and writes back into clipboard | |
const run = ()=>c.writeSync( | |
format( | |
resolve( | |
JSON.parse( | |
c.readSync() | |
) | |
) | |
) | |
); | |
run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment