UNPKG

json-to-schema-www

Version:

A tool to translate json to json-schema

85 lines (75 loc) 1.96 kB
(function() { function isObject(obj) { return Object.prototype.toString.call(obj, null) === '[object Object]' } function returnBaseType(val) { if (typeof val == null) { return 'string' } return typeof val } function dealArray(arr, schema) { schema.type = 'array' const props = schema.items = {} if (!arr.length) return if (arr.length === 1) { parse(arr[0], props) return } // deal array items const { ...temp } = arr[0] const tempKeys = Object.keys(temp) let itemKeys = null let extraKeys = null for (let i = 1; i < arr.length; i ++) { itemKeys = Object.keys(arr[i]) if (!itemKeys.every(k => tempKeys.includes(k))) { extraKeys = itemKeys.filter(k => !tempKeys.includes(k)) extraKeys.forEach((k) => { temp[k] = arr[i][k] }) } } parse(temp, props) } function dealObject(obj, schema) { schema.type = 'object' schema.required = [] const props = schema.properties = {} for (let k in obj) { const item = obj[k] let kSchema = props[k] = {} if (k.startsWith('*')) { delete props[k] k = k.substr(1) schema.required.push(k) kSchema = props[k] = {} } parse(item, kSchema) } } function parse(json, schema) { if (Array.isArray(json)) { dealArray(json, schema) } else if (isObject(json)) { dealObject(json, schema) } else { schema.type = returnBaseType(json) schema.description = '' if (json != null) { schema.template = json } } } function ejs(data) { const schema = {} parse(data, schema) return schema } if(typeof module !== 'undefined' && typeof module === 'object' && module.exports !== 'undefined'){ module.exports = ejs } if(typeof window !== 'undefined' && typeof window === 'object'){ window.easyJsonSchema = ejs } })()