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 know how to call functions. It covers what JSON.stringify does with ordinary data. Unsupported values, replacers, indentation, and toJSON each get their own chapter later.
The working model
JSON.stringify(value) walks a value and returns a string of JSON text. The string has no extra whitespace, so you can send it over HTTP, write it to a file, or put it in localStorage.
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"The result is text. You can no longer write text.name. To get an object back, you parse the text, which the next chapter covers.
How each type is written
| JavaScript value | JSON output |
|---|---|
| `"hi"` | `"hi"` (double-quoted, with escapes) |
| `42`, `-1.5` | `42`, `-1.5` |
| `true` / `false` | `true` / `false` |
| `null` | `null` |
| `{ a: 1 }` | `{"a":1}` (keys always double-quoted) |
| `[1, 2]` | `[1,2]` |
| `new Number(3)`, `new String("x")` | `3`, `"x"` (wrapper objects are unwrapped) |
You don't have to pass an object. Primitives work at the top level too:
console.log(JSON.stringify("hi")); // "hi" (the string includes the quotes)
console.log(JSON.stringify(42)); // 42
console.log(JSON.stringify(true)); // true
console.log(JSON.stringify(null)); // null
console.log(JSON.stringify([1, "two", false, null])); // [1,"two",false,null]Strings are escaped for you
Quotes, backslashes, and control characters inside strings are escaped automatically. Don't build JSON by concatenating strings, because a single stray quote will produce invalid output.
const note = { text: 'She said "hi"\nthen left' };
console.log(JSON.stringify(note));
// {"text":"She said \"hi\"\nthen left"}
// Fragile: breaks as soon as the value contains a quote
const bad = '{"text":"' + note.text + '"}';Which properties are included
Only own, enumerable, string-keyed properties are written. That leaves out:
- Inherited properties from the prototype chain.
- Properties defined as non-enumerable, for example with
Object.defineProperty. - Symbol keys.
- Extra named properties on arrays. Only the index slots are written.
const base = { inherited: true };
const obj = Object.create(base);
obj.own = 1;
Object.defineProperty(obj, "hidden", { value: 2, enumerable: false });
obj[Symbol("id")] = 3;
console.log(JSON.stringify(obj)); // {"own":1}
const list = [10, 20];
list.label = "scores";
console.log(JSON.stringify(list)); // [10,20]Key order
Keys come out in the same order as Object.keys. Integer-like keys come first in ascending order, and the remaining string keys follow in insertion order. Two objects with the same contents can therefore produce different strings, which is why comparing JSON strings is not a reliable equality check.
console.log(JSON.stringify({ b: 1, a: 2, 10: "x", 2: "y" }));
// {"2":"y","10":"x","b":1,"a":2}
console.log(JSON.stringify({ a: 1, b: 2 }) === JSON.stringify({ b: 2, a: 1 }));
// falseThe full signature
JSON.stringify(value, replacer, space);The optional replacer filters or transforms values, and space adds indentation. Later chapters cover both. For now, pass only value.
Exercise
What does this print, and why? const p = Object.create({ role: "admin" }); p[3] = "c"; p.name = "Ada"; p[1] = "a"; console.log(JSON.stringify(p));
Show answer
It prints {"1":"a","3":"c","name":"Ada"}. The inherited role property is skipped because only own enumerable properties are serialized. The integer-like keys 1 and 3 come first in ascending order, followed by name.
Exercise
A teammate writes const body = '{"msg":"' + input + '"}'; to send user input to an API. What goes wrong when input is He said "ok", and what should they write instead?
Show answer
The quotes inside input end the JSON string early, so the body becomes invalid JSON. They should write JSON.stringify({ msg: input }), which escapes the quotes and returns {"msg":"He said \"ok\""}.