DEV Community

Vasanth S
Vasanth S

Posted on • Edited on

How JSON.stringify() Works in JavaScript

JSON.stringify() is Javascript built-in method that converts Javascript object or value into JSON string.

The syntax of JSON.stringify is
JSON.stringify(value, replacer, space)

Parameters:

  • value – The object or value to convert.
  • replacer (optional) – A function or array that filters properties.
  • space (optional) – Adds indentation, spaces, or line breaks for readability.

Why Do We Use JSON.stringify()?

  • To send data to APIs - Most APIs expect data in JSON format.
  • To store data - When saving object in localstorage or database, they must be string.
  • To debug easily - It’s helpful to see object structures as strings.

Real-World Use Case

fetch("/api/save", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "David", email: "david@example.com" })
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)