JavaScript and JSON
How to Format JSON in JavaScript
Learn how to format JSON in JavaScript with JSON.stringify, JSON.parse, indentation options, and practical browser and Node.js examples.
What does formatting JSON do?
Formatting JSON adds line breaks and indentation to a JSON string so that objects, arrays, and nested values are easier to read. It does not change the data. The standard JavaScript tools for this work areJSON.parse() and JSON.stringify().
utility. For a ready-made editor, try the JSON Beautifier.
Format JSON in Node.js
Node.js uses the same built-in JSON methods. You can format an object before writing it to a file or printing it in a terminal.
import { writeFile } from "node:fs/promises";
const settings = { port: 3000, debug: false };
const formattedJson = JSON.stringify(settings, null, 2);
await writeFile("settings.json", formattedJson + "\n");Adding a final newline makes generated files easier to inspect in command-line tools and version control.
Important JavaScript values to remember
JSON is stricter than a JavaScript object literal. JSON does not support comments, functions, undefined, NaN, or single-quoted strings. When stringifying an object, properties with undefined values and functions are omitted, whileundefined values inside arrays become null.
Check the formatted output when these values matter. Formatting is not a lossless conversion for every JavaScript value.
Quick reference
- Use
JSON.parse(text)to turn valid JSON text into a JavaScript value. - Use
JSON.stringify(value, null, 2)for readable JSON. - Wrap parsing in
try...catchwhen input may be invalid. - Use
textContentfor displaying JSON text in the browser.
You can also paste JSON into the online JSON formatter to inspect its structure without writing a custom script.