DEV Community

Sajin Joe J
Sajin Joe J

Posted on

JSON.stringify() and JSON.parse() in Javascript

In JavaScript, JSON.stringify() and JSON.parse() are used to convert data between a JavaScript object and a JSON string.

1. JSON.stringify()
It converts a JavaScript object into a string.
Example :

let student = {
    name: "Sajin Joe",
    age: 25
};

let result = JSON.stringify(student);

console.log(result);
console.log(typeof result);
Enter fullscreen mode Exit fullscreen mode

Output :

{"name":"Sajin Joe","age":25}
string
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • student is a JavaScript object.
  • JSON.stringify(student) converts the object into a string.
  • typeof result returns "string".

2. JSON.parse()
It converts a JSON string back into a JavaScript object.

let student = '{"name":"Sajin Joe","age":25}';

let result = JSON.parse(student);

console.log(result);
console.log(result.name);
console.log(typeof result);
Enter fullscreen mode Exit fullscreen mode

Output:

{ name: 'Sajin Joe', age: 25 }
Sajin Joe
object
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • student contains JSON text as a string.
  • JSON.parse(student) converts it into a JavaScript object.
  • result.name accesses the object's name property. Remember: parse = String → Object.

3. Real-world example: Shopping cart
When using localStorage, these methods work together.

let cart = [
    { name: "Laptop", price: 50000 },
    { name: "Mouse", price: 500 }
];

// Save cart
localStorage.setItem("cart", JSON.stringify(cart));

// Get cart
let savedCart = JSON.parse(localStorage.getItem("cart"));

console.log(savedCart);
Enter fullscreen mode Exit fullscreen mode

How it works:

  1. JSON.stringify(cart) converts the cart array into a string so it can be stored.
  2. localStorage.setItem() saves that string.
  3. localStorage.getItem("cart") retrieves the stored string.
  4. JSON.parse() converts the string back into an array.

Easy way to remember for interviews:

  • stringify → Save data.
  • parse → Read data back as JavaScript values.

Top comments (0)