Skip to content

Instantly share code, notes, and snippets.

@maxpatiiuk
Created November 20, 2021 23:16
Show Gist options
  • Save maxpatiiuk/d4ef9186113913cfe5a8732834645144 to your computer and use it in GitHub Desktop.
Save maxpatiiuk/d4ef9186113913cfe5a8732834645144 to your computer and use it in GitHub Desktop.
Basic inference of JSON Schema from a JSON object
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