DEV Community

Cover image for Using JSON.stringfy() Method in js
s mathavi
s mathavi

Posted on • Edited on

Using JSON.stringfy() Method in js

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]])
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

localStorage.setItem("user", JSON.stringify(user));
Enter fullscreen mode Exit fullscreen mode

To get it back,

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

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}
Enter fullscreen mode Exit fullscreen mode

Using space parameter (pretty print)

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

Output:

{
  "name": "Mathavi",
  "age": 25
}
Enter fullscreen mode Exit fullscreen mode

What JSON.stringify() cannot do?

  • undefined value-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!

Top comments (0)