← ToolBox
/ JSON Schema 生成器
🌙
🧬 JSON Schema 生成器
根据 JSON 数据自动生成 JSON Schema,支持类型推断、必填字段、数组项推断。
美化
压缩
校验
复制
清空
示例
缩进
2 空格
4 空格
Tab
输出结果
等待输入...
已复制
const SAMPLE = JSON.stringify({name:"Alice",age:30,active:true,tags:["a","b"],address:{city:"SH",zip:"200000"}, spouse:null}, null, 2); function inferSchema(v){ if(v === null) return {"type":"null"}; if(Array.isArray(v)) return {"type":"array","items": v.length ? inferSchema(v[0]) : {}}; const t = typeof v; if(t === 'string') return {"type":"string"}; if(t === 'number') return Number.isInteger(v) ? {"type":"integer"} : {"type":"number"}; if(t === 'boolean') return {"type":"boolean"}; if(t === 'object'){ const props = {}, required = []; for(const k in v){ props[k] = inferSchema(v[k]); required.push(k); } return {"type":"object","properties":props,"required":required}; } return {}; } function doBeautify(){ setErr(''); try{ const data = JSON.parse(document.getElementById('input').value); const schema = {"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{},"required":[]}; const inferred = inferSchema(data); Object.assign(schema, inferred); if(inferred.type === 'object'){ schema.properties = inferred.properties || {}; schema.required = inferred.required || []; } setOut(JSON.stringify(schema, null, getIndent())); }catch(e){ setErr('❌ ' + e.message); } } function doMinify(){ setErr(''); try{ const data = JSON.parse(document.getElementById('input').value); const schema = {"$schema":"http://json-schema.org/draft-07/schema#"}; Object.assign(schema, inferSchema(data)); setOut(JSON.stringify(schema)); }catch(e){ setErr('❌ ' + e.message); } } function doValidate(){ setErr(''); try{ const data = JSON.parse(document.getElementById('input').value); const schema = inferSchema(data); const stats = ['类型: ' + schema.type]; if(schema.type === 'object') stats.push('字段数: ' + (schema.properties ? Object.keys(schema.properties).length : 0)); if(schema.type === 'array') stats.push('项类型: ' + (schema.items && schema.items.type ? schema.items.type : '未知')); setErr('✅ 有效 JSON,' + stats.join(',')); setOut(JSON.stringify(schema, null, getIndent())); }catch(e){ setErr('❌ ' + e.message); } } function getIndent(){const v=document.getElementById('indent').value;return v==='tab'?'\t':' '.repeat(parseInt(v));} function setOut(s){document.getElementById('output').textContent=s;} function setErr(s){const e=document.getElementById('err');e.textContent=s||'';e.className='err'+(s?'':' ok');} function clearAll(){document.getElementById('input').value='';setOut('等待输入...');setErr('');} function loadSample(){document.getElementById('input').value=SAMPLE;doBeautify();}