JSON Formatter & Validator: how it works and how to build one
Format, validate, minify, stringify and parse JSON. This guide explains what happens behind the button and shows the code, so you can build your own.
What it does
Paste JSON or open a .json file to pretty-print it with 2 or 4 spaces, minify it for transport, or check that it is valid. Errors show the line and column so you can find a missing comma quickly. Stringify turns any text into an escaped JSON string, and Parse does the reverse, which is handy for payloads that were stringified twice.
When to use it
- Reading API responses
- Finding a missing comma
- Making config files tidy
- Shrinking JSON for storage
How to use it
- Paste JSON into the input, or click Open file to load a .json file.
- Pick Format, Minify, Stringify or Parse.
- Copy the result or download it as a file.
Try it free in your browser, nothing is uploaded: https://eskillsfy.com/tools/json-formatter
How it works
Formatting JSON is two steps: parse the text into a JavaScript value with JSON.parse, then turn it back into text with JSON.stringify and an indent. If parsing throws, the text isn’t valid JSON, and the error message tells you where.
Minifying is the same with no indent. Sorting keys walks the value and rebuilds every object with its keys in order.
Build it yourself
Here is the core of the tool. It has no dependencies unless noted, so you can paste it into any TypeScript or JavaScript project.
jsonFormat.ts (ts)
export function formatJson(text: string, indent = 2, sortKeys = false) {
const value = JSON.parse(text); // throws SyntaxError with the position
const sort = (v: unknown): unknown =>
Array.isArray(v) ? v.map(sort)
: v && typeof v === "object"
? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sort((v as Record<string, unknown>)[k])]))
: v;
return JSON.stringify(sortKeys ? sort(value) : value, null, indent);
}
export const minifyJson = (text: string) => JSON.stringify(JSON.parse(text));
Make it production-ready
- Turn the error’s character position into a line and column.
- Add a file picker with file.text() and drag and drop.
- Debounce the formatter so huge files don’t freeze typing.
Questions
Is my JSON sent to a server?
No. Everything runs in your browser, so private API responses never leave your machine.
Why does it say Unexpected token?
JSON needs double quotes around keys and strings and no trailing commas. The error message shows the line and column of the first problem.
Free, runs in your browser, nothing is uploaded.