Loading lessons...
JSON Stringify
JSON Stringify
JSON.stringify() converts a JavaScript object or array into a JSON string.
The basics
const person = { name: "Ada", age: 36 };
const json = JSON.stringify(person);
// '{"name":"Ada","age":36}'
Why stringify?
- Send data to a server (it needs text).
- Save data in localStorage.
- Log or debug objects.
Stringifying arrays
JSON.stringify([1, 2, 3]); // "[1,2,3]"
What cannot be stringified
- Functions are omitted.
- undefined values are omitted.
- Symbols are omitted.
JSON.stringify({ a: function() {}, b: 5 });
// '{"b":5}'
Pretty printing
Pass a spacing number for readable output:
JSON.stringify(person, null, 2);
TL;DR
- JSON.stringify turns objects into JSON text.
- Send or store data as strings.
- Functions, undefined, and symbols are dropped.
- A spacing argument makes output readable.