What does JSON.stringify do?

Question

In the context of this exercise, what does JSON.stringify do?

Answer

JSON.stringify is a method that converts a JavaScript object into a string. One use of the method is to store the object as a string in a database, and then convert back to an object when obtaining it.

For example,

JSON.stringify({ a: 1, b: 2 });
// "{"a": 1, "b": 2}"
12 Likes

What are some of the benefits or uses of doing this?

7 Likes

From my personal experience, it’s useful to parse data so it can be easier used in making tables, graphs and other methods of displaying them.

4 Likes

You can also use this method to console.log the data that is prone to get altered later in the code. For example, if you console.log the same object many times in the code, you’ll get the same result each time. When you stringify the result, you can view the object’s state at each console.log.

Sometimes, in coding, you may probably need to compare two javascript objects, and the result will thus be used to perform another operation. This can be achieved, by stringifying both objects and comparing the contents, rather than comparing the key-value pairs of each object.

Sample demo scenario is illustrated as shown below, comparing two objects, using stringify to achieve our desired results

let obj1 = {
name:  "Nat",

profession : "Informaticien",

};

let obj2 = {

name:  "Nat",

profession : "Informaticien",

};

let result = obj1 === obj2;

console.log("Result1 = " + result);

let result2 = JSON.stringify(obj1) === JSON.stringify(obj2);

console.log("Result2 = " + result2);

Result 1 yields (false)

Result 2 yields (true)

6 Likes

As mentioned before, if you want to store an object in Redis, you need to convert the object to a string.

It is very usefull to shallow clone the object itself.
In the example, it serves to clean the Object from it’s default properties that are inherited from the prototype.

Nowdays with the advances of ECS6, we have structuredClone to use instead.

1 Like