JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JSON Stringify


When working with modern web applications, data constantly moves between the browser, server, storage, and APIs. JavaScript objects are easy to work with inside the code, but they cannot be sent or stored directly in many situations. This is where JSON.stringify() becomes essential. It converts JavaScript values into JSON formatted strings that can be stored, transmitted, or logged safely.

In this tutorial, you will learn what JSON.stringify() is, why it is important, how it works, its syntax, detailed examples, common mistakes, best practices, and real world use cases.

What Is JSON.stringify()

JSON.stringify() is a JavaScript method that converts a JavaScript object, array, or value into a JSON string. This JSON string can then be sent to a server, saved in browser storage, or used for data exchange between systems.

In simple terms, JSON.stringify() turns JavaScript data into text that follows JSON rules.

Why JSON.stringify() Is Important

JSON.stringify() is important because it allows developers to:

  • Send data to servers using AJAX or Fetch

  • Store structured data in localStorage or sessionStorage

  • Save application state

  • Convert objects into readable text

  • Exchange data between frontend and backend

  • Work efficiently with APIs

Without this method, JavaScript objects would not be compatible with many storage and communication mechanisms.

Basic Syntax of JSON.stringify()

JSON.stringify(value, replacer, space)
  • value is the data to convert into JSON

  • replacer is optional and controls which properties are included

  • space is optional and adds formatting for readability

The method returns a JSON formatted string.

Simple JSON.stringify() Example

let user = {
    name: "Amit",
    age: 27
};

let jsonText = JSON.stringify(user);
console.log(jsonText);

Output:

{"name":"Amit","age":27}

The object is now converted into a string.

Stringifying Arrays

let cities = ["Delhi", "Mumbai", "Bengaluru"];
let jsonCities = JSON.stringify(cities);

console.log(jsonCities);

Arrays are converted correctly into JSON array strings.

Stringifying Nested Objects

let employee = {
    name: "Neha",
    department: "IT",
    address: {
        city: "Pune",
        state: "Maharashtra"
    }
};

let data = JSON.stringify(employee);
console.log(data);

Nested objects remain structured in JSON format.

Using JSON.stringify() with Numbers and Booleans

let info = {
    active: true,
    score: 92
};

let result = JSON.stringify(info);
console.log(result);

Primitive values are converted without issues.

JSON.stringify() and localStorage

Browser storage accepts only strings. JSON.stringify() is required to store objects.

let profile = {
    name: "Rahul",
    role: "Designer"
};

localStorage.setItem("profile", JSON.stringify(profile));

Reading the data later requires JSON.parse().

JSON.stringify() with sessionStorage

let settings = {
    theme: "dark",
    language: "en"
};

sessionStorage.setItem("settings", JSON.stringify(settings));

This is commonly used for temporary user preferences.

Using JSON.stringify() with AJAX

When sending data to a server, objects must be stringified.

let data = {
    name: "Suman",
    email: "suman@gmail.com"
};

var xhr = new XMLHttpRequest();
xhr.open("POST", "save.php", true);
xhr.setRequestHeader("Content-Type", "application/json");

xhr.send(JSON.stringify(data));

This is a standard pattern in API communication.

Using JSON.stringify() with Fetch API

fetch("submit.php", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        product: "Laptop",
        price: 55000
    })
});

Fetch makes heavy use of JSON.stringify().

Formatting JSON Output with Space Parameter

The space parameter improves readability.

let user = {
    name: "Kiran",
    age: 24,
    city: "Jaipur"
};

let formatted = JSON.stringify(user, null, 4);
console.log(formatted);

This is helpful for debugging and logging.

Using the Replacer Parameter

The replacer allows filtering properties.

let student = {
    name: "Anjali",
    marks: 85,
    grade: "A"
};

let result = JSON.stringify(student, ["name", "grade"]);
console.log(result);

Only selected properties are included.

Replacer Function Example

let data = {
    name: "Vikas",
    salary: 50000
};

let json = JSON.stringify(data, function (key, value) {
    if (key === "salary") {
        return undefined;
    }
    return value;
});

console.log(json);

This is useful for hiding sensitive data.

What JSON.stringify() Ignores

Some values are skipped automatically.

  • Functions

  • Undefined values

  • Symbols

let obj = {
    name: "Ramesh",
    greet: function () {}
};

console.log(JSON.stringify(obj));

The function is ignored.

Handling Dates with JSON.stringify()

Dates are converted to strings.

let event = {
    date: new Date()
};

console.log(JSON.stringify(event));

Dates must be restored manually using JSON.parse() logic.

Common Mistakes

  • Trying to stringify circular references

  • Expecting functions to be included

  • Forgetting to parse stored JSON

  • Storing sensitive data in plain text

  • Overusing formatting in production

Avoiding these mistakes prevents errors and security risks.

Best Practices

  • Always validate data before stringifying

  • Avoid storing passwords or tokens

  • Use formatting only for debugging

  • Keep JSON payloads minimal

  • Combine with JSON.parse() properly

These practices ensure clean and secure applications.

JSON.stringify() vs toString()

toString() does not produce valid JSON.

  • JSON.stringify() creates standard JSON

  • toString() creates unreadable strings

  • JSON output is portable and structured

Always prefer JSON.stringify() for data exchange.

Performance Considerations

  • Large objects increase processing time

  • Avoid unnecessary stringify operations

  • Optimize object size

  • Cache results when possible

Efficient usage improves performance.

Real World Applications

JSON.stringify() is widely used in:

  • API request payloads

  • Local and session storage

  • State management systems

  • Logging and debugging

  • Offline applications

  • Form data submission

It is a core method in modern JavaScript development.

Browser Support

JSON.stringify() is supported by all modern browsers and is safe to use in production environments.

Summary of JSON Stringify

The JSON.stringify() method is essential for converting JavaScript objects into JSON strings that can be stored, transmitted, or shared between systems. It plays a critical role in API communication, browser storage, and application state management. By understanding its syntax, optional parameters, common pitfalls, and best practices, you can use JSON.stringify() effectively to build reliable, secure, and high performance JavaScript applications.


Practice Questions

  1. Convert the following JavaScript object into a JSON string using JSON.stringify():

let user = { name: "Vicky", age: 28, isDeveloper: true };
  1. Stringify the following array of numbers and print the resulting JSON string:

let scores = [88, 95, 72, 100];
  1. Convert this nested object into a JSON string and ensure it is formatted with 2-space indentation:

let user = { name: "Sanjana", age: 26, address: { city: "Delhi", zipcode: 110001 } };
  1. Given this object, exclude the password property when converting to JSON:

let user = { username: "vicky123", password: "secret", email: "vicky@example.com" };
  1. Create a JSON string from this array of objects representing books:

let books = [
  { title: "Learn JS", author: "Vicky" },
  { title: "Master PHP", author: "Sanjana" }
];
  1. Convert a JavaScript object containing functions and undefined values into a JSON string. Observe what happens to these values:

let obj = { name: "Vicky", greet: () => "Hello", age: undefined };
  1. Store the following JavaScript object in local storage as a JSON string:

let settings = { theme: "dark", fontSize: 16, notifications: true };
  1. Stringify a JavaScript object and then parse it back using JSON.parse(). Verify that you can access one of its properties. Example object:

let product = { id: 101, name: "Laptop", price: 55000 };
  1. Convert this nested array into a JSON string and print the result:

let data = [["HTML", "CSS"], ["JavaScript", "React"]];
  1. Use a replacer function to stringify the following object but exclude the salary property:

let employee = { name: "Vicky", role: "Developer", salary: 50000 };

Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top