Validate Value by Schema
JavaScript
Hard
3 views
Problem Description
Two JSON values are given on two lines: schema and value. Schema has field type (number|string|boolean|null|array|object). For array, schema can have items. For object, schema can have props and required list. Extra keys are allowed. Print YES if value matches schema else NO.
Input Format
Line1: schema JSON. Line2: value JSON.
Sample Test Case
Input:
{"type":"array","items":{"type":"number"}}
[1,2,3]
Constraints
Total schema+value nodes up to 2e5.
Official Solution
const fs=require('fs');const txt=fs.readFileSync(0,'utf8');const lines=txt.split(/\
?\
/);const sLine=(lines[0]||'').trim();const vLine=lines.slice(1).join('\
').trim();if(!sLine||!vLine)process.exit(0);const schema=JSON.parse(sLine);const val=JSON.parse(vLine);const isObj=v=>v!==null && typeof v==='object' && !Array.isArray(v);const check=(sch,v)=>{if(!sch||typeof sch!=='object')return false;const t=sch.type; if(t==='null')return v===null; if(t==='number')return typeof v==='number' && Number.isFinite(v); if(t==='string')return typeof v==='string'; if(t==='boolean')return typeof v==='boolean'; if(t==='array'){if(!Array.isArray(v))return false;const item=sch.items;for(const x of v){if(!check(item,x))return false;}return true;} if(t==='object'){if(!isObj(v))return false;const req=Array.isArray(sch.required)?sch.required:[];for(const k of req){if(!(k in v))return false;}const props=isObj(sch.props)?sch.props:{};for(const k of Object.keys(props)){if(k in v && !check(props[k],v[k]))return false;}return true;} return false;};process.stdout.write(check(schema,val)?'YES':'NO');
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!