Set JSON Value by Path
JavaScript
Hard
5 views
Problem Description
You get a JSON object, a path like a.b[0].c, and a JSON value. Set that path in the object (create objects/arrays when needed). Print updated object as JSON.
Input Format
Line1: JSON object. Line2: path string. Line3: JSON value.
Output Format
One line JSON output.
Sample Test Case
Output:
{\"a\":{\"b\":[{\"c\":5}]}}
Constraints
Total nodes after creation 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[1]||'').trim();const vLine=lines.slice(2).join('\
').trim();if(!oLine||!path||!vLine)process.exit(0);const obj=JSON.parse(oLine);const value=JSON.parse(vLine);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++;tokens.push({t:'i',v:Number(path.slice(i,j))});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(let ti=0;ti<tokens.length;ti++){const tok=tokens[ti];const last=ti===tokens.length-1;const next=tokens[ti+1];if(tok.t==='k'){if(cur===null||typeof cur!=='object'||Array.isArray(cur)){}if(last){cur[tok.v]=value;break;}if(!(tok.v in cur) || cur[tok.v]===null || typeof cur[tok.v]!=='object'){cur[tok.v]=(next&&next.t==='i')?[]:{};}cur=cur[tok.v];}else{if(!Array.isArray(cur)){}if(last){cur[tok.v]=value;break;}while(cur.length<=tok.v)cur.push(null);if(cur[tok.v]===null || typeof cur[tok.v]!=='object'){cur[tok.v]=(next&&next.t==='i')?[]:{};}cur=cur[tok.v];}}process.stdout.write(JSON.stringify(obj));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!