Skip to content

Instantly share code, notes, and snippets.

@japsu
Created May 24, 2016 09:35
Show Gist options
  • Save japsu/31da89d5e827a64bf096e5d776fd4e19 to your computer and use it in GitHub Desktop.
Save japsu/31da89d5e827a64bf096e5d776fd4e19 to your computer and use it in GitHub Desktop.
schemaByExample – generate JSON schema from example object
import _ from 'lodash';
export default function schemaByExample(example) {
if (_.isArray(example)) {
return {
type: 'array',
items: schemaByExample(example[0])
};
} else if (_.isPlainObject(example)) {
return {
type: 'object',
required: _.keys(example),
properties: _.mapValues(example, schemaByExample)
};
} else if (_.isString(example)) {
return {
type: 'string'
};
} else if (_.isNumber(example)) {
return {
type: 'number'
};
} else if (_.isRegExp(example)) {
return {
type: 'string',
pattern: example
};
} else if (_.isBoolean(example)) {
return {
type: 'boolean'
};
}
return undefined;
};
import assert from 'assert';
import { validate } from 'jsonschema';
import schemaByExample from '.';
describe('schemaByExample', () => {
it('produces a JSON schema that matches the given example object', () => {
const example1 = {};
const expectedSchema1 = { type: 'object', properties: {}, required: [] };
const generatedSchema1 = schemaByExample(example1);
assert.deepEqual(generatedSchema1, expectedSchema1);
assert(validate(example1, generatedSchema1).valid);
const example2 = { a: 5 };
const expectedSchema2 = {
type: 'object',
required: ['a'],
properties: {
a: { type: 'number' }
}
};
const generatedSchema2 = schemaByExample(example2);
assert.deepEqual(generatedSchema2, expectedSchema2);
assert(validate(example2, generatedSchema2).valid);
const example3 = {
response: {
body: [{
customer: {}
}]
}
};
const expectedSchema3 = {
type: 'object',
required: ['response'],
properties: {
response: {
type: 'object',
required: ['body'],
properties: {
body: {
type: 'array',
items: {
type: 'object',
required: ['customer'],
properties: {
customer: {
type: 'object',
required: [],
properties: {}
}
}
}
}
}
}
}
};
const generatedSchema3 = schemaByExample(example3);
assert.deepEqual(generatedSchema3, expectedSchema3);
assert(validate(example3, generatedSchema3).valid);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment