Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

JSON.stringify()

Posted in JSON Tutorial
Updated on May 28, 2024
By Mari Selvan
πŸ‘οΈ 40 - Views
⏳ 4 mins
πŸ’¬ 1 Comment
JSON.stringify()

Photo Credit to CodeToFun

πŸ™‹ Introduction

JavaScript Object Notation (JSON) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.

One of the key methods in JavaScript for working with JSON is JSON.stringify(). This method converts a JavaScript object or value to a JSON string.

πŸ€” What is JSON.stringify()?

The JSON.stringify() method converts a JavaScript object or value to a JSON string. This is particularly useful for sending data over a network or for storing data in a format that can easily be parsed later.

πŸ’‘ Syntax

Syntax
Copied
Copy To Clipboard
JSON.stringify(value, replacer, space)
  • value: The value to convert to a JSON string.
  • replacer (optional): A function that alters the behavior of the stringification process, or an array of strings and numbers that acts as a whitelist for selecting the properties of the object to be included in the JSON string.
  • space (optional): A string or number that's used to insert white space into the output JSON string for readability purposes.

Basic Usage

Here’s a simple example of how to use JSON.stringify():

JavaScript
Copied
Copy To Clipboard
const obj = { name: "John", age: 30, city: "New York" };
const jsonString = JSON.stringify(obj);
console.log(jsonString);

πŸ’» Output

In this example, JSON.stringify() converts the JavaScript object obj into a JSON string.

Output
{"name":"John","age":30,"city":"New York"}

Using the replacer Parameter

The replacer parameter can be a function or an array. As a function, it is called for each property of the object, and can modify or filter the properties that are included in the resulting JSON string.

Example with Function Replacer:

JavaScript
Copied
Copy To Clipboard
const obj = { name: "John", age: 30, city: "New York" };

function replacer(key, value) {
  if (typeof value === "string") {
    return undefined;
  }
  return value;
}

const jsonString = JSON.stringify(obj, replacer);
console.log(jsonString);

πŸ’» Output

In this example, the replacer function filters out properties with string values.

Output
{"age":30}

Example with Array Replacer:

JavaScript
Copied
Copy To Clipboard
const obj = { name: "John", age: 30, city: "New York" };
const jsonString = JSON.stringify(obj, ["name", "city"]);
console.log(jsonString);

πŸ’» Output

In this example, only the name and city properties are included in the resulting JSON string.

Output
{"name":"John","city":"New York"}

Using the space Parameter

The space parameter is used to add indentation, white space, and line breaks to the output JSON string for readability.

Example with Space Parameter:

JavaScript
Copied
Copy To Clipboard
const obj = { name: "John", age: 30, city: "New York" };
const jsonString = JSON.stringify(obj, null, 2);
console.log(jsonString);

πŸ’» Output

In this example, the JSON string is formatted with an indentation of 2 spaces, making it easier to read.

Output
{
  "name": "John",
  "age": 30,
  "city": "New York"
}

Handling Circular References

When an object contains circular references, JSON.stringify() will throw an error. Circular references occur when an object references itself, directly or indirectly.

JavaScript
Copied
Copy To Clipboard
const obj = {};
obj.a = obj;

try {
  JSON.stringify(obj);
} catch (error) {
  console.log("Error:", error.message);
}

πŸ’» Output

To handle circular references, you can use a library like circular-json or write a custom replacer function.

Output
Error: Converting circular structure to JSON

πŸŽ‰ Conclusion

The JSON.stringify() method is an essential tool for converting JavaScript objects into JSON strings. Understanding how to use its parameters can help you control the stringification process, ensuring that your data is properly formatted and includes only the desired properties.

Whether you're sending data over a network, storing it, or logging it for debugging, JSON.stringify() is a versatile and powerful method to have in your JavaScript toolkit.

πŸ‘¨β€πŸ’» Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
πŸ‘‹ Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy