Using JSON.stringfy() Method in js



This content originally appeared on DEV Community and was authored by s mathavi

Hello everyone!!!!
Today, we are going to learn about one of the most important and useful methods in JavaScript — JSON.stringify(). Whether you’re saving user data to local Storage, sending data to an API, or just trying to understand how objects can be converted into strings, this method is something every web developer must know.
We’ll learn this topic step-by-step .
What is JSON.stringify()?
JSON = JavaScript Object Notation
It’s a way to store data in a text format, easily readable and transferable.
This is especially useful when:

  • want to store data in Local Storage
  • Need to send data to a backend API Syntax:
JSON.stringify(value[, replacer[, space]])

It is the way to stored the Data
{
“name”: “Mathavi”,
“age”: 25
}
Why use JSON.stringify()?
JavaScript objects can’t be directly stored in localStorage or sent via API. They need to be converted into a string.

const obj = { name: "Mathavi" };
const str = JSON.stringify(obj);
localStorage.setItem("data", str);

Store In LocalStorage:
localStorage.setItem(“user”, user); // Won’t work correctly
So,

localStorage.setItem("user", JSON.stringify(user));

To get it back,

const data = localStorage.getItem("user");
const parsedData = JSON.parse(data);
console.log(parsedData.name); // Mathavi

Using replacer parameter

const user = { name: "Mathavi", age: 25, gender: "female" };
const result = JSON.stringify(user, ["name", "age"]);
console.log(result); // {"name":"Mathavi","age":25}

Using space parameter (pretty print)

const obj = { name: "Mathavi", age: 25 };
console.log(JSON.stringify(obj, null, 2));

Output:

{
  "name": "Mathavi",
  "age": 25
}

What JSON.stringify() cannot do?

  • undefined value-Skipped
  • Function in object-Skipped
  • Function in object-Skipped.

Conclusion
In this Blog, Convert JavaScript objects to strings,Save them in localStorage,Retrieve and use them again.

!!!…Thank you so much for reading…!!!

Until then, happy:) coding!


This content originally appeared on DEV Community and was authored by s mathavi