DEV Community

Devanshu Biswas
Devanshu Biswas

Posted on

I Built a JSON Formatter & Validator in the Browser (No Library)

A JSON formatter sounds like a weekend project — and it is, because the browser does the hard part. Here's a live formatter + validator with syntax highlighting and real error locations, no library.

🧾 Try it (paste JSON): https://dev48v.infy.uk/solve/day15-json-formatter.html

Format = parse then re-stringify

const obj = JSON.parse(input);          // validate (throws if invalid)
const pretty = JSON.stringify(obj, null, 2);  // 2-space indent
Enter fullscreen mode Exit fullscreen mode

That's the entire formatter. JSON.stringify(obj) with no third arg gives you minify for free.

Validation is "did parse throw?"

Wrap JSON.parse in try/catch. On failure, the error message often includes a position — turn that into a line/column and show the offending snippet, so the user sees where it broke (trailing comma, single quotes, unquoted key — the usual suspects).

Syntax highlighting

Tokenize the pretty output with a regex and wrap keys / strings / numbers / booleans / null in colored spans. ~15 lines.

One safety rule

Never eval() JSON. JSON.parse is safe; eval runs arbitrary code.

🔨 Full build (parse → stringify → highlight → minify → error position) on the page: https://dev48v.infy.uk/solve/day15-json-formatter.html

Part of SolveFromZero. 🌐 https://dev48v.infy.uk

Top comments (0)