Files and data
Pretty-print JSON without changing its data
Parse a JSON document and stringify it with an indentation argument to improve readability. Keep the original when formatting data whose exact byte representation or large numeric precision matters.
Worked example
Node.js example · save as example.mjs and run node example.mjs
const compact = '{"name":"demo","values":[1,2]}';
const value = JSON.parse(compact);
const formatted = JSON.stringify(value, null, 2);
console.log(formatted);
console.log(JSON.stringify(JSON.parse(formatted)) === compact);How it works
Indentation inserts whitespace outside JSON strings. The formatted document represents the parsed value in a more readable layout. Parsing the result provides a basic round-trip check for this fixture, where the numbers and property order are uncomplicated.
Limits and mistakes
Parsing can already lose precision for integers outside the Number safe range, and duplicate object keys do not survive as separate fields. Formatting also changes bytes, so signatures or hashes of the original file no longer apply.
Check the result
Expect a multiline document and true. Check a string containing spaces to ensure formatting does not alter string contents. Use a precision-preserving parser if the source contains large numeric identifiers.
Sources
Reference documentation for the behavior used in this guide: