Sequence NODE_236
MediumValidate JSON and Print Errors
Node.js
Technical Specification
Create a script that tries to parse a JSON file and reports whether it is valid or prints the parse error.
Input/Output Samples
Input:node validate.js broken.json
Output:Invalid JSON: Unexpected token ...
Optimal Logic Path
const fs = require("fs");
const file = process.argv[2];
if (!file) {
console.error("Usage: node validate.js <file>");
process.exit(1);
}
try {
const text = fs.readFileSync(file, "utf8");
JSON.parse(text);
console.log("Valid JSON");
} catch (err) {
console.error("Invalid JSON:", err.message);
process.exit(1);
}Architectural Deep-Dive
We catch parse errors and make it easy to validate JSON config or data files.