Stringify JSON in JavaScript and Node.js

How JSON.stringify turns JavaScript values into JSON text, what it drops or rejects, how to pretty-print, and how to print objects in Node.js and browsers.

Converting a JavaScript value to a JSON string comes down to one built-in function: JSON.stringify. It works the same way in browsers and in Node.js, and it is the standard way to turn objects into text you can send over a network, write to a file, store, or log. This review covers what the function changes, where the conversion loses information, and when a different way of printing an object serves you better.

Is JSON.stringify the right tool for your use?

Use it when the text has to be read by another program. Its main benefit is that the output is standard JSON, so any JSON parser in any language can read it back. The main tradeoff is that the conversion is lossy for anything outside JSON's small set of types: strings, numbers, booleans, null, arrays and plain objects. Functions, undefined, symbols, Maps, Sets and class instances are dropped, flattened or converted, and BigInt values and circular references make it throw an error.

A different approach is better in three situations. If you are debugging in Node.js, util.inspect or console.dir shows types that JSON cannot represent. If the reader is a person rather than a program, a short prose summary or a table is usually clearer than raw JSON. If your data depends on Dates, Maps, BigInts or class instances surviving a round trip, plain JSON.stringify is not enough without a replacer and a matching reviver.

What the conversion actually changes

JSON.stringify serializes. It reads a value and returns a new string; the original object is not modified. Characters inside your strings pass through unchanged except where JSON requires escaping: double quotes, backslashes, control characters such as newlines and tabs, and unpaired surrogate code units. Non-ASCII text such as accented letters and emoji is written as-is, not converted to escape sequences. Nothing is reversed, reordered within strings, or restyled.

const user = { name: "Ada", roles: ["admin"], active: true };

JSON.stringify(user);
// '{"name":"Ada","roles":["admin"],"active":true}'

Property order follows JavaScript's own ordering rules. Keys that look like array indexes come first in ascending numeric order, followed by other string keys in the order they were added. If you compare JSON output as plain text, two objects with the same data can produce different strings if their keys were added in a different order.

JSON.stringify({ b: 1, a: 2, 2: "x", 1: "y" });
// '{"1":"y","2":"x","b":1,"a":2}'

Pretty-printing with the space argument

The third argument controls indentation. A number sets that many spaces per level, capped at 10. A string such as a tab is used as the indent, and only its first 10 characters are used. The indentation only affects how the output looks: JSON parsers ignore whitespace between tokens, so compact and indented output parse to the same data.

console.log(JSON.stringify(user, null, 2));
// {
//   "name": "Ada",
//   "roles": [
//     "admin"
//   ],
//   "active": true
// }

console.log(JSON.stringify(user, null, "\t")); // tab-indented

What gets dropped or converted

Input value | Inside an object | Inside an array | As the top-level value
undefined | property omitted | null | returns undefined, not a string
function | property omitted | null | returns undefined
Symbol | property omitted | null | returns undefined
NaN, Infinity, -Infinity | null | null | "null"
-0 | 0 | 0 | "0"
Date | ISO 8601 string via toJSON | ISO 8601 string | ISO 8601 string
Map, Set | {} | {} | "{}"
Error | {} (message and stack are not enumerable) | {} | "{}"
BigInt | throws TypeError | throws TypeError | throws TypeError
const input = {
  a: undefined,
  b: () => 1,
  c: NaN,
  d: new Date(0),
  e: new Map([["k", 1]]),
  f: [undefined, Symbol("s")],
};

JSON.stringify(input);
// '{"c":null,"d":"1970-01-01T00:00:00.000Z","e":{},"f":[null,null]}'

Symbol-keyed properties and non-enumerable properties are also skipped. Parsing the result does not reverse these changes: a Date comes back as a string, a Map comes back as an empty object, and omitted properties are simply gone.

Values that throw instead of converting

Two inputs cause a TypeError instead of producing output: BigInt values and objects that refer back to themselves. Wrap stringify calls in try/catch where the input is not under your control. For BigInt, a replacer function can turn the value into a string first. For circular structures, you need to remove the cycle, or use a replacer that tracks objects it has already seen and skips them.

JSON.stringify({ n: 10n });
// TypeError: BigInt values are not serializable by default

const node = {};
node.self = node;
JSON.stringify(node);
// TypeError: circular structure

JSON.stringify(
  { n: 10n },
  (key, value) => (typeof value === "bigint" ? value.toString() : value)
);
// '{"n":"10"}'

Controlling output with a replacer or toJSON

The second argument is the replacer. An array of key names acts as an allowlist, which is a simple way to keep fields such as tokens out of logs. A function receives each key and value and returns the value to write; returning undefined omits that property. The first call to the function receives an empty-string key and the whole value. An object can also define its own toJSON method, which stringify calls before serializing it. This is how Date produces its ISO string.

const account = { id: 7, name: "Ada", token: "abc123" };
JSON.stringify(account, ["id", "name"]);
// '{"id":7,"name":"Ada"}'

class Money {
  constructor(cents) { this.cents = cents; }
  toJSON() { return (this.cents / 100).toFixed(2); }
}
JSON.stringify({ total: new Money(1999) });
// '{"total":"19.99"}'

const err = new Error("boom");
JSON.stringify(err);                                       // '{}'
JSON.stringify({ name: err.name, message: err.message });  // '{"name":"Error","message":"boom"}'

If you already have a JSON string, don't stringify it again

A common mistake behind searches for converting JSON to a string is that the value is already a string. Response bodies, file contents and values read from localStorage are often JSON text already. Stringifying them again wraps the text in quotes and escapes every inner quote, which produces a JSON string literal instead of an object. Parse the text if you need the data, and pass it along unchanged if you only need the text.

const text = '{"ok":true}';

console.log(JSON.stringify(text));
// "{\"ok\":true}"   <- double-encoded

console.log(JSON.parse(text).ok);
// true

Printing objects in Node.js

In Node.js, console.log does not print JSON. It formats objects with util.inspect, which leaves keys unquoted, uses single quotes for strings, shows types such as Map and Date, and by default stops after two levels of nesting, showing deeper objects as [Object]. That output is good for reading but is not valid JSON. Use console.dir or util.inspect with depth set to null to see everything, and use JSON.stringify when the output has to be parsed by something else.

const util = require("node:util");
const nested = { a: { b: { c: { d: 1 } } } };

console.log(nested);
// { a: { b: { c: [Object] } } }

console.dir(nested, { depth: null });
// { a: { b: { c: { d: 1 } } } }

console.log(util.inspect(nested, { depth: null }));

console.log(JSON.stringify(nested, null, 2)); // valid, parseable JSON

Printing objects in the browser

Browser developer consoles show a logged object as an expandable tree. In many consoles, the contents are read when you expand the tree, not when the log line ran, so a later change to the object can appear in an earlier log. Logging JSON.stringify(obj, null, 2) captures a fixed text snapshot at that moment. To show JSON on a page, put the string in a pre element using textContent. Do not use innerHTML, so that any markup inside the data is shown as text rather than run as HTML.

const pre = document.createElement("pre");
pre.textContent = JSON.stringify(data, null, 2);
document.body.append(pre);

Will the output stay readable after copying or sharing?

At the character level, yes. Because stringify writes non-ASCII characters as-is and never reorders code points inside strings, accented letters, combining marks and multi-code-point emoji such as a ZWJ sequence come through unchanged. If the source contains a decomposed letter (a base letter plus a combining accent), the output keeps it decomposed. The function does not normalize text. The one exception is an unpaired surrogate. Current engines write it as a lowercase escape sequence instead of producing invalid text, a behavior standardized in ES2019. Older runtimes may differ.

console.log(JSON.stringify({ word: "café", mark: "✓", face: "👩‍💻" }));
// {"word":"café","mark":"✓","face":"👩‍💻"}

console.log(JSON.stringify("\uD83D"));
// "\ud83d"

Indentation is less reliable. Losing it never breaks parsing, but some destinations may collapse spaces, convert tabs, or wrap long lines, and that makes nested structure harder to read. This review did not test any specific chat app, ticketing system or document editor. Check the destination yourself, and use a code block or a file attachment where one is available.

Embedding JSON in an HTML script element needs extra care. JSON.stringify does not escape the less-than sign, so a string value containing a closing script tag can end the element early. Escaping that character keeps the JSON valid and the page intact.

const safe = JSON.stringify(data).replace(/</g, "\\u003c");

For accessibility, raw JSON is dense with punctuation, and indentation carries its structure visually. How a given screen reader announces braces, quotes and nesting depends on the product and its punctuation settings. No assistive-technology testing was available for this review, so no specific behavior is claimed here. When the audience is not developers, provide a plain-text equivalent alongside or instead of the JSON, such as a sentence summary, a list of fields and values, or a table.

Evidence and gaps

  • The behavior described here comes from the documented semantics of JSON.stringify in the ECMAScript standard and from Node.js's documented console and util.inspect behavior, not from measurements.
  • No performance figures are given. Serialization speed and memory use for large objects were not measured.
  • No specific sharing destination or assistive technology was tested. Treat the copy-and-paste and accessibility guidance as general cautions, not verified results.
  • The examples show expected output for current engines. Runtimes older than ES2019 may handle unpaired surrogates differently.

Verdict

JSON.stringify keeps meaning intact for plain data such as strings, finite numbers, booleans, null, arrays and plain objects, and its output works anywhere JSON is accepted. Indentation makes it readable without changing the data. It is not a general way to print any JavaScript value: it silently drops or flattens several types and throws on others. Use util.inspect or console.dir for debugging in Node.js, add a replacer or toJSON where your types need it, avoid stringifying text that is already JSON, and give human readers a plain-text version when raw JSON is not the right format for them.