Safe JSON Parse
JavaScript
Easy
4 views
Problem Description
Input has two lines: first is a JSON string, second is a default value as JSON. If first line parses, print parsed JSON (stringified). If it fails, print the default JSON as output.
Input Format
Line1: raw string (not JSON). Line2: default JSON value.
Output Format
One line: JSON stringified output.
Constraints
Default value line is valid JSON.
Official Solution
const fs=require('fs');const txt=fs.readFileSync(0,'utf8');const lines=txt.split(/\
?\
/);const raw=lines[0]??'';const defLine=lines.slice(1).join('\
').trim();const def=defLine?JSON.parse(defLine):null;let out=def;try{out=JSON.parse(raw);}catch(e){}process.stdout.write(JSON.stringify(out));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!