DEV Community

Cover image for What is JSON.stringify()? A Beginner’s Guide with Examples
Megha M
Megha M

Posted on

What is JSON.stringify()? A Beginner’s Guide with Examples

When building modern web applications, working with JavaScript objects is inevitable. But what happens when you need to send data to a server, store it locally, or debug it in a readable format?

That’s where JSON.stringify() comes into play — a powerful method that transforms JavaScript objects into JSON strings. In today’s blog, we’ll explore what it does, how it works, and how to use it like a pro.

What is JSON.stringify()?

JSON.stringify() is a built-in JavaScript method that converts a JavaScript object, array, or value into a JSON-formatted string.

Syntax

JSON.stringify(value, replacer, space);

Why Use JSON.stringify()?

  • Sending Data to APIs: Most APIs accept JSON-formatted data.
  • Saving to Local Storage: localStorage and sessionStorage only store strings.
  • Debugging: Easily inspect object structure in a readable format.

Getting Started with an Example

const user = {
  name: "Megha",
  age: 25,
  isMember: true
};

const jsonString = JSON.stringify(user);
console.log(jsonString);
Enter fullscreen mode Exit fullscreen mode

Output:

{"name":"Megha","age":25,"isMember":true}
Enter fullscreen mode Exit fullscreen mode

Working with Nested Objects

const product = {
  id: 101,
  name: "Saree",
  details: {
    color: "Red",
    size: "Free"
  }
};

console.log(JSON.stringify(product));
Enter fullscreen mode Exit fullscreen mode

Output:

{"id":101,"name":"Saree","details":{"color":"Red","size":"Free"}}
Enter fullscreen mode Exit fullscreen mode

Pretty Printing with space:

console.log(JSON.stringify(product, null, 2));
Enter fullscreen mode Exit fullscreen mode

Output:

{
  "id": 101,
  "name": "Saree",
  "details": {
    "color": "Red",
    "size": "Free"
  }
}
Enter fullscreen mode Exit fullscreen mode

Filtering Properties with replacer

const user = {
  name: "Megha",
  age: 25,
  password: "secret"
};

const filteredJSON = JSON.stringify(user, ["name", "age"]);
console.log(filteredJSON);
Enter fullscreen mode Exit fullscreen mode

Output:

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

What JSON.stringify() Ignores

const data = {
  name: "Test",
  date: new Date(),
  sayHello: function () {
    return "Hello!";
  },
  something: undefined
};

console.log(JSON.stringify(data));
Enter fullscreen mode Exit fullscreen mode

Output:

{"name":"Test","date":"2025-07-30T02:19:04.000Z"}
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

JSON.stringify() is an essential tool in every JavaScript developer’s toolkit. It allows you to:

  • Serialize complex objects
  • Communicate with APIs
  • Store structured data
  • Clean up logs for debugging

Next time you need to convert your JavaScript objects into a string — remember, JSON.stringify() has you covered!

Top comments (0)