Sub topic 2
Turning Values into JSON Text with JSON.stringify
This chapter assumes you know JavaScript objects, arrays, and primitive types, and that you can read arrow functions. It covers what JSON.stringify does with ordinary data: which properties it reads, in what order, how it escapes strings, and what it produces for built-in types such as Map and Error. Later chapters cover the optional replacer and space arguments, the toJSON method, and values that JSON cannot represent. This chapter touches those topics only where you need them to understand the basic behavior.
The Signature and the Return Value
JSON.stringify(value, replacer, space) takes a JavaScript value and returns a string of JSON text. Only the first argument is required. The output is compact by default, with no spaces or line breaks.
const user = { name: "Ada", age: 36, tags: ["math", "code"] };
const text = JSON.stringify(user);
console.log(text); // {"name":"Ada","age":36,"tags":["math","code"]}
console.log(typeof text); // "string"
const copy = JSON.parse(text);
console.log(copy.tags[1]); // "code"
console.log(copy === user); // falseThe result is plain text. Nothing in it links back to user, so parsing it gives you a new, independent object. This is why JSON.stringify is the standard way to put structured data into places that only hold strings: HTTP request bodies, localStorage, log lines, files, and message queues.
The return type is almost always string. The exception is a top-level value that JSON cannot represent, such as undefined, a function, or a symbol. In those cases the function returns undefined instead of a string. The chapter on unsupported values covers this in detail. For now, remember that code like JSON.stringify(x).length can throw if x might be undefined.
How Each Kind of Value Is Written
The algorithm looks at the type of each value and writes the matching JSON form. Objects and arrays are walked recursively, so nesting depth does not change the rules.
Primitives
Primitives can be stringified on their own. The result is valid JSON text, because a JSON document does not have to be an object.
console.log(JSON.stringify("hi")); // "hi" (quotes are part of the output)
console.log(JSON.stringify(42)); // 42
console.log(JSON.stringify(true)); // true
console.log(JSON.stringify(null)); // null
console.log(JSON.stringify(-0)); // 0
console.log(JSON.stringify(1e21)); // 1e+21
console.log(JSON.stringify(0.1 + 0.2)); // 0.30000000000000004Numbers are written the same way String(number) writes them, which is why 1e21 keeps exponent notation. The sign of -0 is lost, so -0 comes back as 0 after a round trip. That rarely matters, but it can break code that checks Object.is(x, -0).
The string case confuses people at first. JSON.stringify("hi") returns a four-character string: a quote, h, i, and another quote. Those quotes are what make the text valid JSON.
Wrapper Objects
new Number(3), new String("x"), and new Boolean(false) are unwrapped to their primitive values before they are written:
console.log(JSON.stringify([new Number(3), new String("x"), new Boolean(false)]));
// [3,"x",false]Arrays
Arrays are written in index order from 0 to length - 1. Holes in sparse arrays become null. Extra non-index properties on an array are ignored.
console.log(JSON.stringify([1, , 3])); // [1,null,3]
const arr = [1, 2];
arr.label = "pair";
console.log(JSON.stringify(arr)); // [1,2]Which Object Properties Are Included
For non-array objects, JSON.stringify writes own, enumerable, string-keyed properties. Each of those three words removes something:
- Own leaves out inherited properties from the prototype chain.
- Enumerable leaves out properties defined with
enumerable: false. - String-keyed leaves out symbol keys.
Getters are called, and their return values are written.
const obj = Object.create({ inherited: 1 });
obj.own = 2;
Object.defineProperty(obj, "hidden", { value: 3, enumerable: false });
obj[Symbol("s")] = 4;
Object.defineProperty(obj, "computed", {
get() { return this.own * 10; },
enumerable: true
});
console.log(JSON.stringify(obj)); // {"own":2,"computed":20}Class instances follow the same rule. Fields set in the constructor are own enumerable properties, so they appear. Getters and methods live on the prototype, so they do not. Private #fields are not properties at all, so they never appear.
class Point {
#id = 99;
constructor(x, y) {
this.x = x;
this.y = y;
}
get length() {
return Math.hypot(this.x, this.y);
}
}
console.log(JSON.stringify(new Point(3, 4))); // {"x":3,"y":4}The output has no record of the class. Parsing it gives back a plain object without length or any methods. The chapter on revivers shows how to rebuild class instances.
Property Order
The output order follows JavaScript's standard property order. Integer-like keys such as "1" and "2" come first, sorted ascending. All other string keys follow in insertion order.
const o = { b: 1, 2: "two", a: 2, 1: "one" };
console.log(JSON.stringify(o)); // {"1":"one","2":"two","b":1,"a":2}This order is deterministic, but it depends on insertion order. Two objects with the same contents can produce different strings if their keys were added in a different order. If you compare JSON strings, hash them, or use them as cache keys, sort the keys first. The chapter on replacers shows one way to do this.
String Escaping
Strings in the output are wrapped in double quotes. A few characters are escaped:
| Character | Output |
|---|---|
| `"` | `\"` |
| `\` | `\\` |
| newline, tab, carriage return, backspace, form feed | `\n`, `\t`, `\r`, `\b`, `\f` |
| other control characters U+0000 to U+001F | `\u00XX` |
| lone surrogate halves | `\udXXX` |
| everything else, including `/`, `é`, and emoji | written as-is |
console.log(JSON.stringify('He said "hi"\n')); // "He said \"hi\"\n"
console.log(JSON.stringify("tab\there")); // "tab\there"
console.log(JSON.stringify("\u0007")); // "\u0007"
console.log(JSON.stringify("café 🎉")); // "café 🎉"
console.log(JSON.stringify("\uD800")); // "\ud800"Escaping lone surrogates became standard in ES2019. Because of it, the output is always well-formed UTF-16 and safe to encode as UTF-8. Non-ASCII text is not escaped, so the receiving side must decode the bytes as UTF-8. For HTTP, send Content-Type: application/json, which defaults to UTF-8.
Built-in Objects That Serialize Surprisingly
Many built-in types store their data in internal slots or in non-enumerable properties. JSON.stringify cannot see those, so these types often turn into {} without any error.
console.log(JSON.stringify(new Map([["a", 1]]))); // {}
console.log(JSON.stringify(new Set([1, 2]))); // {}
console.log(JSON.stringify(/ab+c/)); // {}
console.log(JSON.stringify(new Error("boom"))); // {}
console.log(JSON.stringify(new Uint8Array([1, 2]))); // {"0":1,"1":2}
console.log(JSON.stringify(new Date(0))); // "1970-01-01T00:00:00.000Z"Date works because it has a built-in toJSON method. The toJSON chapter explains that hook. For the other types, convert the value to plain data yourself before you stringify it:
const scores = new Map([["ada", 10], ["alan", 8]]);
const ids = new Set([3, 1, 2]);
const err = new Error("boom");
const payload = {
scores: Object.fromEntries(scores), // string keys only
scoreEntries: [...scores], // keeps any key type
ids: [...ids],
error: { name: err.name, message: err.message }
};
console.log(JSON.stringify(payload));
// {"scores":{"ada":10,"alan":8},"scoreEntries":[["ada",10],["alan",8]],"ids":[3,1,2],"error":{"name":"Error","message":"boom"}}The Error case causes real trouble in logging code. JSON.stringify({ err }) logs {"err":{}}, and the error message is lost.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Storing an object without stringifying | `localStorage` holds `"[object Object]"` | Store `JSON.stringify(obj)` and read it back with `JSON.parse` |
| Stringifying twice | Output looks like `"{\"a\":1}"` with escaped quotes | Stringify once, at the boundary where data leaves your code |
| Building JSON by string concatenation | Invalid output when a value contains `"` or a newline | Build an object and let `JSON.stringify` escape it |
| Expecting `Map`, `Set`, or `Error` to serialize | `{}` in the output | Convert to arrays or plain objects first |
| Comparing JSON strings for equality | Equal data compares as unequal | Sort keys, or compare structurally |
Double stringification usually happens when a helper already serializes the body and the caller serializes it again:
const once = JSON.stringify({ a: 1 });
const twice = JSON.stringify(once);
console.log(once); // {"a":1}
console.log(twice); // "{\"a\":1}"
console.log(typeof JSON.parse(twice)); // "string", not "object"A typical correct use at an HTTP boundary looks like this:
const payload = { name: "Ada", roles: ["admin"] };
const options = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload)
};
console.log(options.body); // {"name":"Ada","roles":["admin"]}Exercises
Exercise
What does console.log(JSON.stringify({ z: 1, 10: "ten", a: 2, 3: "three" })) print, and why is it in that order?
Show answer
It prints {"3":"three","10":"ten","z":1,"a":2}. Integer-like keys come first in ascending numeric order. The remaining string keys follow in the order they were inserted.
Exercise
A class Temperature sets this.celsius in its constructor and defines get fahrenheit() on the class. What does JSON.stringify(new Temperature(20)) produce, and how would you include fahrenheit without adding a toJSON method?
Show answer
It produces {"celsius":20}, because the getter lives on the prototype and is not an own property. To include it, serialize a plain object you build yourself, for example JSON.stringify({ celsius: t.celsius, fahrenheit: t.fahrenheit }). Another option is to define fahrenheit as an own enumerable getter with Object.defineProperty on the instance.
Exercise
A logger runs JSON.stringify({ level: "error", err }) where err is new Error("disk full"). The log line is {"level":"error","err":{}}. Explain the cause and write a fix.
Show answer
The message, name, and stack properties of an Error are non-enumerable, so JSON.stringify skips them and writes an empty object. Fix it by copying the fields explicitly: JSON.stringify({ level: "error", err: { name: err.name, message: err.message, stack: err.stack } }).
Exercise
Predict the output of JSON.stringify([new Set([1]), [ , 2], -0, "a\"b"]).
Show answer
[{},[null,2],0,"a\"b"]. The Set has no enumerable own properties, so it becomes {}. The array hole becomes null. -0 is written as 0. The double quote inside the string is escaped as \".