JSON.stringify
Learn to convert an object into a JSON string with JSON.stringify.
Turning an object into text
To convert a JavaScript object into a text format, use the built-in stringify method. Pass the object as a parameter; the method returns a text string.
const user = { name: 'Alex' };
const text = stringify(user);
// text === '{"name": "Alex"}'The returned text can be used anywhere: written to a file, sent to a server or saved in storage.
Readable text with indentation
If you pass a number as the third parameter to stringify, the result is indented. This makes the data easier for humans to read.
const text = stringify(user, null, 2);The second parameter is a replacer function or a list of keys; pass null if you do not need it. Indentation is only for display; it does not matter when you parse the data back.
Exercise Turn the object into text
Turn the settings object into text and assign it to text. Use the built-in stringify method.
Show example solution
Call stringify with settings.
Example solution:
const text = stringify(settings);
Test yourself
-
What does stringify({a: 1}) return?
stringify({a: 1})- An object
- A number
- null
- A string
Show answer
A string — Correct! stringify turns an object into a string.
-
Produce indented text
const text = stringify(user, ____, 2);Show answer
const text = stringify(user, null, 2); -
Match methods to their job
- stringify
- object to text
- parse
- text to object
- trim
- trims string edges
- join
- joins an array