JSON stringify() Method in JavaScript

Let’s find out and explore the power of the JSON.stringify() method in JavaScript.

But wait, what is JSON.stringify, and what does it do?

In this article, you will discover how to use this method to convert JavaScript values into JSON strings.

So, read on to gain a deeper understanding of this powerful tool in JavaScript.

What is JSON stringify()?

The JSON.stringify() is a method in JavaScript that converts a JavaScript value into a JSON string.

This is especially handy when you need to transmit data to a web server, as the data must be in string format.

Syntax

JSON.stringify(value, replacer, space)
 ✅

Parameter

value (Required)

The value to convert to a JSON string.

replacer (Optional

A function that alters the behavior of the stringification process, or an array of String and Number objects that

act as a filter to specify which properties of the value object should be included in the JSON string.

When this value is either null or not provided, all properties of the object are encompassed within the resulting JSON string.

space (Optional) 

A String or Number object that’s used to insert white space into the output JSON string for readability purposes.

Return value

A JSON string representing the given value, or undefined.

What does JSON.stringify() do?

Here’s how it operates:

Stringify a JavaScript Object

If you have a JavaScript object, you can convert it into a string using this method.

For example, if you have an object like this:

let obj = { name: "Itsourcecode", age: 18, city: "New York" };

You can convert it into a string with:

 const myJSON = JSON.stringify(obj);

Stringify a JavaScript Array

It’s also possible to stringify JavaScript arrays. For example, if you have an array like this:

 const arr = ["English", "Math", "Science", "Programming"];

You can convert it into a string with:

 const myJSON = JSON.stringify(arr);

Storing Data

When storing data, the data has to be in a certain format, and text is always one of the legal formats.

JSON enables the conversion of JavaScript objects into textual format.

Here’s an example code of how you can use this method to convert a JavaScript object into a JSON string for storage:

// Define a JavaScript object
let obj = {
  name: "Code",
  age: 18,
  gender: "Male"
};

// Use JSON.stringify() to convert the object into a JSON string
let objJSON = JSON.stringify(obj); ✅

// Now you can store this string in a database or file
console.log(objJSON); 

// When you need to use this data, you can retrieve it and use JSON.parse() to convert it back into an object
let retrievedobj = JSON.parse(objJSON); 

console.log(retrievedobj);  

Output:

{"name":"Code","age":18,"gender":"Male"} (stored data)
 
{ name: 'Code', age: 18, gender: 'Male' } (retrieved data)

Exceptions

You should know that Date objects are not allowed in JSON. This method will convert any dates into strings. Also, it will remove any functions from a JavaScript object.

Any functions present within a JavaScript object will be eliminated by this method.

JSON.stringify() converts date objects into strings

Here’s an example code:

let obj = {
  name: "Code",
  age: 18,
  gender: "Male",
  today: new Date() ✅
};

let jsonString = JSON.stringify(obj);  

console.log(jsonString);

Output:

{"name":"Code","age":18,"gender":"Male","today":"2023-08-24T01:31:05.516Z"}

JSON.stringify() will remove any functions from a JavaScript object

Here’s an example:

let obj = {
 name: "Code",
 age: function () {return 30;}, 
 gender: "Male"
  
};

let jsonString = JSON.stringify(obj);  

console.log(jsonString);

Output:

{"name":"Code","gender":"Male"}

📌Please note that the this method can return undefined when passing in “pure” values like JSON.stringify(() => {}) or JSON.stringify(undefined).

How to stringify JSON?

To stringify a JSON object in JavaScript, you can use this method.

Here’s a basic example:

let obj = {
name: "Code",
age: 18,
gender: "Male"
};

let jsonString = JSON.stringify(obj); 

console.log(jsonString);

In this example, JSON.stringify(obj) takes the object obj and converts it into a JSON string. The resulting string (jsonString) would be:

{"name":"Code","age":18,"gender":"Male"}

This method is particularly useful when you need to send data to a server, as the data needs to be a string.

It’s also handy for storing data because the data has to be in a certain format, and text is always one of the legal formats.

How to use JSON stringify() method in JavaScript?

Basic Usage

Here’s a basic example of how to use this method:

// Define a JavaScript object
let student = {
name: "Itsourcecode",
age: 18,
city: "USA"
};

// Use JSON.stringify() to convert it into a JSON string
let studentJSON = JSON.stringify(student); 

// Log the result
console.log(studentJSON);

In this example, JSON.stringify(student) takes the student object and converts it into a JSON string. The resulting string (studentJSON) is a textual representation of the object.

Output:

{"name":"Itsourcecode","age":18,"city":"USA"}

Advanced Usage

You can also pass a replacer function as the second argument to JSON.stringify() to filter-out values:

let student = {
name: "Itsourcecode",
age: 18,
city: "USA"
};

let studentJSON = JSON.stringify(student, (key, value) =>  {
if (key === 'age') return undefined ;
return value;
});

console.log(studentJSON);

In this example, the replacer function is used to remove the “age” property from the resulting JSON string.

Output:

{"name":"Itsourcecode","city":"USA"}

You can also use the third argument to pretty-print the resulting JSON string:

let student = {
name: "Itsourcecode",
age: 18,
city: "USA"
};

let studentJSON = JSON.stringify(student, null, 2); ✅ 

console.log(studentJSON);

In this example, passing “2” as the third argument tells JSON.stringify() to add two white spaces of indentation to each level in the resulting JSON string.

Output:

{
  "name": "Itsourcecode",
  "age": 18,
  "city": "USA"
}

Conclusion

In conclusion, the article discusses the significance and usage of the JSON.stringify() method in JavaScript.

This method is used to convert JavaScript values, such as objects and arrays, into JSON strings. It is particularly useful for transmitting data to servers or storing data in a text-based format.

We are hoping that this article provides you with enough information that help you understand the JSON stringify.

If you want to dive into more JavaScript topics, check out the following articles:

Thank you for reading Itsourcecoders 😊.

Leave a Comment