JSON.stringify()

JSON.stringify() is the opposite of JSON.parse(). While JSON.parse() converts a JSON string into a JavaScript object, JSON.stringify() converts a JavaScript object or array into a JSON-formatted string.

This is necessary because when sending data to a server, saving data to a file, or storing data in browser storage, the data must first be converted into a plain text string. Servers and storage systems do not understand JavaScript objects — they understand strings.

Simple Analogy

Imagine packing items into a box before shipping them. The items are your JavaScript object, and the box is the JSON string. JSON.stringify() packs everything neatly into the box so it can be sent to the destination.

Syntax of JSON.stringify()

JSON.stringify(value, replacer, space)
  • value — the JavaScript object or array to convert (required)
  • replacer — an optional filter to include or exclude certain keys
  • space — an optional number or string for formatting (indentation)

Basic Example

const person = {
  name: "Meera Nair",
  age: 27,
  city: "Kochi"
};

const jsonString = JSON.stringify(person);

console.log(jsonString);
// Output: {"name":"Meera Nair","age":27,"city":"Kochi"}

The result is a compact JSON string with no spaces.

Formatting the Output with Indentation

The third parameter of JSON.stringify() controls how the output is formatted. Passing a number adds indentation with that many spaces, making the output readable:

const person = {
  name: "Meera Nair",
  age: 27,
  city: "Kochi"
};

const jsonString = JSON.stringify(person, null, 2);

console.log(jsonString);
// Output:
// {
//   "name": "Meera Nair",
//   "age": 27,
//   "city": "Kochi"
// }

Stringifying an Array

const fruits = ["mango", "apple", "guava"];

const jsonString = JSON.stringify(fruits);

console.log(jsonString);
// Output: ["mango","apple","guava"]

Stringifying a Nested Object

const order = {
  orderId: "ORD-2201",
  customer: {
    name: "Suresh Babu",
    phone: "9988776655"
  },
  total: 3200
};

const jsonString = JSON.stringify(order, null, 2);

console.log(jsonString);
// Output:
// {
//   "orderId": "ORD-2201",
//   "customer": {
//     "name": "Suresh Babu",
//     "phone": "9988776655"
//   },
//   "total": 3200
// }

Using the Replacer to Filter Keys

The second parameter (replacer) can be an array of key names to include only specific fields in the output:

const employee = {
  name: "Farhan Khan",
  age: 32,
  salary: 60000,
  department: "HR"
};

const jsonString = JSON.stringify(employee, ["name", "department"]);

console.log(jsonString);
// Output: {"name":"Farhan Khan","department":"HR"}

Only name and department are included. The other keys (age, salary) are excluded.

How JSON.stringify() Handles Different Data Types

JavaScript ValueJSON.stringify() Result
String: "hello""hello"
Number: 4242
Boolean: truetrue
Null: nullnull
Array: [1, 2, 3][1,2,3]
Object: {a: 1}{"a":1}
FunctionExcluded (ignored)
UndefinedExcluded (ignored)
DateConverted to ISO string

Important: Functions and undefined are Excluded

const data = {
  name: "Gopal",
  greet: function() { return "Hello"; },
  score: undefined
};

const jsonString = JSON.stringify(data);

console.log(jsonString);
// Output: {"name":"Gopal"}
// greet and score are ignored

How Dates are Handled

const event = {
  title: "Workshop",
  date: new Date(2025, 0, 15)
};

const jsonString = JSON.stringify(event);

console.log(jsonString);
// Output: {"title":"Workshop","date":"2025-01-15T00:00:00.000Z"}

JavaScript Date objects are automatically converted into ISO 8601 string format when stringified.

Common Use Case — Sending Data to a Server

Before sending data to a server using a POST request (for example, a login form), the data must be converted to a string:

const loginData = {
  username: "neha_dev",
  password: "pass@1234"
};

const body = JSON.stringify(loginData);

// Now 'body' can be sent in a fetch/AJAX request
console.log(body);
// Output: {"username":"neha_dev","password":"pass@1234"}

Key Points to Remember

  • JSON.stringify() converts a JavaScript object or array into a JSON string
  • The third parameter controls indentation for pretty-printing
  • Functions and undefined values are automatically excluded from output
  • Dates are converted to ISO 8601 string format
  • The replacer parameter allows filtering specific keys
  • It is the opposite operation of JSON.parse()

Summary

JSON.stringify() is essential whenever data needs to leave the JavaScript environment — whether being sent to a server, stored in localStorage, written to a file, or logged for debugging. It cleanly converts any JavaScript data structure into a portable, text-based JSON string that any system can understand.

Leave a Comment

Your email address will not be published. Required fields are marked *