The json.stringify () method converts a JavaScript object or value to a JSON string.

As a JavaScript developer, json.stringify () is the most common function used for debugging. But what does it do? Couldn’t we use console.log() to do the same thing? Let’s have a try.

// Initialize a user object
const user = {` "name" : "Prateek Singh", "age" : 26`
}

// [object Object]
console.log(user);

Copy the code

Oh! Console.log () did not help us print the results we expected. It prints [Object object], because the default conversion from object to string is [Object object]. Therefore, we use json.stringify () to first convert the object to a string and then print it in the console, as shown below.

// Initialize a user object
const user = {` "name" : "Prateek Singh", "age" : 26`
}

// "{ "name" : "Prateek Singh", "age" : 26 }"
console.log(JSON.stringify(user));

Copy the code

In general, it is common for developers to use the Stringify function, as we did above. But I’m going to let you in on some hidden secrets that will make your development a lot easier.

Second argument (array)

Yes, the stringify function can also take a second argument. It is an array of keys for objects to print in the console. Looks simple? Let’s dig a little deeper. We have an object called product and we want to know the value of the name property of product. When we print it out:

console.log(JSON.stringify(product))

Copy the code

It will print the following result.

{"id":"0001"."type":"donut"."name":"Cake"."ppu": 0.55."batters": {"batter": [{"id":"1001"."type":"Regular"}, {"id":"1002"."type":"Chocolate"}, {"id":"1003"."type":"Blueberry"}, {"id":"1004"."type":"The Devil 's Food"}},"topping": [{"id":"5001"."type":"None"}, {"id":"5002"."type":"Glazed"}, {"id":"5005"."type":"Sugar"}, {"id":"5007"."type":"Powdered Sugar"}, {"id":"5006"."type":"Chocolate with Sprinkles"}, {"id":"5003"."type":"Chocolate"}, {"id":"5004"."type":"Maple"}}]Copy the code

The name key is hard to find in the logs because the console displays a lot of useless information. As the object gets larger, it becomes more difficult to find properties. The second argument to the stringify function is useful here. Let’s rewrite the code and see the results.

// {"name" : "Cake"}
console.log(JSON.stringify(product,['name' ])

Copy the code

That solves the problem. Instead of printing the entire JSON object, we can print only the desired properties by passing the desired keys as an array in the second argument.

The second argument (function)

We can also pass in a function as a second argument. It evaluates each key-value pair based on the logic written in the function. If undefined is returned, no key-value pairs are printed. Please refer to examples for a better understanding.

const user = {
  "name" : "Prateek Singh"."age" : 26
}
Copy the code

/ / ` results
// { "age" : 26 }

Copy the code

Only age is printed because the function returns undefined if typeOf is a String.

The third parameter is a number

The third argument controls the spacing of the last string. If the argument is a number, each level in stringification will indent that number of space characters.

// Note: '--' is used instead of Spaces for comprehension purposes
JSON.stringify(user, null.2);
/ / {
// --"name": "Prateek Singh", 
// --"age": 26,
// --"country": "India"
// }

Copy the code

The third argument is a string

If the third argument is string, it will be used instead of the space character shown above.

// Note that '**' is used instead of Spaces
JSON.stringify(user, null.2);
/ / {
// **"name": "Prateek Singh", 
// **"age": 26,
// **"country": "India"
// }

Copy the code

ToJSON method

We have a method called toJSON that can be a property of any object. Json.stringify returns the result of this function and serializes it, rather than converting the entire object to a string. See the example below.

const user = {
  firstName : "Prateek".lastName : "Singh".age : 26,
  toJSON() {
    return {
      fullName: `The ${this.firstName} + The ${this.lastName}`}}}// "{ "fullName" : "Prateek Singh"}
console.log(JSON.stringify(user));

Copy the code

Here we can see that it prints only the result of the toJSON function, not the whole object.

I hope you’ve learned some basic features of Stringify ().

This work is reproduced (read the original text)