Get JSON Value by Path
JavaScript
Hard
6 views
Problem Description
You get a JSON object, then a path string like a.b[0].c. Print the value at that path as JSON. If path does not exist, print null.
Input Format
Line1: JSON object. Line2: path string.
Output Format
One line JSON output.
Sample Test Case
Input:
{\"a\":{\"b\":[{\"c\":5}]}}
a.b[0].c
Constraints
Path 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);const obj=JSON.parse(oLine);let tokens=[];let i=0;while(i<path.length){if(path[i]==='.')i++;else if(path[i]==='['){i++;let j=i;while(j<path.length && path[j]!==']')j++;const num=path.slice(i,j);tokens.push({t:'i',v:Number(num)});i=j+1;}else{let j=i;while(j<path.length && path[j]!=='.' && path[j]!=='[')j++;tokens.push({t:'k',v:path.slice(i,j)});i=j;}}let cur=obj;for(const tok of tokens){if(cur===null||cur===undefined){cur=null;break;}if(tok.t==='k'){if(typeof cur!=='object'){cur=null;break;}cur=cur[tok.v];}else{if(!Array.isArray(cur)){cur=null;break;}cur=cur[tok.v];}}process.stdout.write(JSON.stringify(cur===undefined?null:cur));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!