JSON.stringify()


JSON is often used to swap data with a web server.

When you send information to a web server, it needs to be in the form of a string.

Change a JavaScript object into a string using JSON.stringify().


Stringify a JavaScript Object

Think about having this object in JavaScript:

const obj = {name: "John", age: 30, city: "New York"};

Use the JavaScript function JSON.stringify() to change it into a string.

const myJSON = JSON.stringify(obj);

The outcome will be a text structured in JSON format.

The variable myJSON has been converted into a string. It's all set to be sent to a server.


Stringify a JavaScript Array

You can also convert JavaScript arrays into strings.

Think about having this array in JavaScript:

const arr = ["John", "Peter", "Sally", "Jane"];

Use the JavaScript function JSON.stringify() to convert it into a string.

const myJSON = JSON.stringify(arr);

The outcome will be a text structured like JSON.

The variable named myJSON has been converted into a string. It's ready to be sent to a server.


Storing Data

When you save information, it needs to follow a specific structure. No matter where you decide to keep it, using text is always a valid way to format the data.

JSON allows storing JavaScript objects as text.


Exceptions

Stringify Dates

In JSON, you can't have date objects. When you use the JSON.stringify() function, it changes any dates into strings.

You can change the string back into a date object when it reaches the recipient.


Stringify Functions

In JSON, you can't use functions as values for objects.

The function called JSON.stringify() removes any functions from a JavaScript object, including both the key and the value.

You don't have to include this step if you change your functions into text before using the JSON.stringify() function.

When you send functions as JSON, they lose their original context. The receiver then has to use eval() to turn them back into functions.