Safe Object Path Read
JavaScript
Medium
3 views
Problem Description
Line1 is JSON object, line2 is a dot path like a.b.c. If path exists print value as JSON. If any step missing, handle error and print null.
Input Format
Line1: JSON object. Line2: path.
Output Format
One line JSON output.
Sample Test Case
Input:
{"a":{"b":2}}
a.b.c
Constraints
Total input length up to 2e5.
Official Solution
const fs=require('fs');const txt=fs.readFileSync(0,'utf8');const lines=txt.split(/\
?\
/);const oLine=(lines[0]||'').trim();const path=(lines.slice(1).join('\
')||'').trim();if(!oLine||!path)process.exit(0);try{const obj=JSON.parse(oLine);let cur=obj;for(const key of path.split('.')){if(cur===null||cur===undefined||typeof cur!=='object'||!(key in cur))throw new Error('MISS');cur=cur[key];}process.stdout.write(JSON.stringify(cur));}catch(e){process.stdout.write('null');}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!