Safe JSON Parse
NodeJS
Hard
3 views
Problem Description
Parse a JSON string safely and print an error message on failure.
Input Format
stdin: one line JSON text.
Output Format
Print JSON keys count or error.
Constraints
Handle invalid JSON without crashing.
Official Solution
const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim();
if (!input) process.exit(0);
try {
const obj = JSON.parse(input);
const count = obj && typeof obj === 'object' ? Object.keys(obj).length : 0;
console.log(count);
} catch (e) {
console.log('Invalid JSON for meetcode');
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!