JavaScript tools
Format JSON safely: know what parsing can change
Format a JSON response with JavaScript, handle invalid input and spot cases where parsing can lose information.
A JSON formatter makes a compact response easier to read. The familiar JavaScript approach parses the text, then serialises the resulting value with indentation. That works well for ordinary application data, but it can change information that was present in the original text. Keep the original whenever the exact representation matters.
Start with a small, valid document
Suppose a booking service returns the following object. The properties describe a workshop and two jobs. They are deliberately small enough to check by eye.
const input = '{"name":"Workshop","jobs":["repair","service"]}'
const value = JSON.parse(input)
const formatted = JSON.stringify(value, null, 2)
console.log(formatted)The third argument requests two spaces of indentation. The second argument is null because this example does not replace or filter any values. The output is:
{
"name": "Workshop",
"jobs": [
"repair",
"service"
]
}You can inspect the jobs without scrolling across a long line. A compact version is also possible with JSON.stringify(value), which omits the indentation argument. Choose readable output while inspecting data and compact output where the receiving system expects it. Neither choice validates the business meaning of the document.
Handle syntax errors explicitly
A trailing comma, a comment or a property name in single quotes can appear in JavaScript source, but those forms are not valid JSON. Parsing should fail visibly rather than quietly returning an empty object. An empty object could be mistaken for a successful response with missing information.
function formatJson(text) {
try {
return { ok: true, text: JSON.stringify(JSON.parse(text), null, 2) }
} catch (error) {
return { ok: false, message: String(error) }
}
}
console.log(formatJson('{"jobs":["repair",]}').ok) // falseThe error wording depends on the JavaScript engine. Use it as a diagnostic for the person editing the input. Avoid writing a test that depends on one exact browser message. A useful formatter also preserves the submitted text after failure so the user can correct the actual mistake.
Watch numbers and repeated keys
A parse-and-stringify round trip is not a text-preserving operation. For example, this integer is outside the range of integers that a JavaScript Number can represent exactly:
const original = '{"id":9007199254740993}'
console.log(JSON.stringify(JSON.parse(original)))
// {"id":9007199254740992}The change happens when the text is converted to a JavaScript value. Extra indentation cannot recover the lost digit. If an identifier must remain exact, agree a string representation with the system that produces it, or use a parser designed to preserve numeric tokens. Do not silently convert a third-party payload without checking its requirements.
Repeated property names create another trap. Parsing {"status":"old","status":"new"} leaves a value whose status is "new". A formatter built on the parsed object cannot reproduce both occurrences. Different whitespace, escape sequences and number spellings can also disappear during serialisation. For signed payloads, audit evidence and debugging captures, retain the original bytes alongside any readable view.
Separate JSON text from JavaScript objects
JSON.stringify can receive JavaScript values that valid JSON text could never contain. Undefined values, functions and circular references therefore need separate consideration. A formatter accepting JSON text should make that input contract clear. A general object inspector is a different tool, with different expectations.
For example, JSON.stringify({note: undefined}) produces an empty object representation, while JSON.stringify([undefined]) produces an array containing null. A circular object throws. Avoid presenting serialisation as a universal way to copy arbitrary objects.
Check the tool before trusting a real payload
Use a harmless fixture first. Check that a valid document formats correctly, invalid syntax remains editable and a large number receives appropriate treatment. Compare the original with the output when the data contains identifiers or repeated keys. These checks reveal more than a polished-looking result alone.
A private API response may contain access tokens, customer details or internal addresses. Before pasting it into any website, establish how that website handles the input. This article does not certify the network behaviour of a particular formatter. A browser interface alone is not evidence that its processing stays on your device.
The MDN references explain the underlying operations: JSON.parse and JSON.stringify. Keep a readable copy for inspection and the untouched original for situations where representation is part of the data.