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


In the previous tutorial, we learned how to parse JSON strings into JavaScript objects using JSON.parse().
Now, it’s time to learn the opposite process: converting JavaScript objects into JSON strings. This is done using JSON.stringify().

JSON.stringify() is essential when you want to send data from your web application to a server or save it in local storage.

What is JSON.stringify()?

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

  • Input: JavaScript object or array

  • Output: JSON string (text format)

Once converted, this string can be sent over the network or stored in files.

Basic Example

let user = {
  name: "Vicky",
  age: 28,
  isDeveloper: true
};

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

Output:

{"name":"Vicky","age":28,"isDeveloper":true}

Explanation:

  • user is a JavaScript object.

  • JSON.stringify(user) converts it into a JSON string.

  • You can now send jsonString to a server or save it in local storage.

Why Do We Need JSON.stringify()?

When sending data via APIs, browsers, or servers, data must be in text format.
JavaScript objects cannot be sent directly — they need to be stringified first.

Example with fetch():

let user = { name: "Vicky", age: 28 };

fetch("https://api.example.com/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(user) // Convert object to JSON string
})
.then(response => response.json())
.then(data => console.log(data));

Without JSON.stringify(), body: user would fail because the server expects a string, not an object.

Stringifying Arrays

You can also convert arrays into JSON strings.

let skills = ["HTML", "CSS", "JavaScript"];
let jsonSkills = JSON.stringify(skills);

console.log(jsonSkills);

Output:

["HTML","CSS","JavaScript"]

After stringifying, this array can be sent to a server or stored just like an object.

Nested Objects

JSON.stringify() works for nested objects as well.

let user = {
  name: "Vicky",
  age: 28,
  address: {
    city: "Mumbai",
    zipcode: 400001
  }
};

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

Output:

{"name":"Vicky","age":28,"address":{"city":"Mumbai","zipcode":400001}}

Nested objects are fully converted into a string, preserving structure.

Formatting JSON Output

JSON.stringify() allows optional parameters to format the output for readability.

Syntax:

JSON.stringify(value, replacer, space)
  • value: The object or array to convert

  • replacer: Optional; a function or array to filter keys

  • space: Optional; number of spaces for indentation

Example:

let user = { name: "Vicky", age: 28, skills: ["HTML","CSS","JS"] };
let formattedJSON = JSON.stringify(user, null, 2);
console.log(formattedJSON);

Output:

{
  "name": "Vicky",
  "age": 28,
  "skills": [
    "HTML",
    "CSS",
    "JS"
  ]
}

This makes the JSON easy to read and debug.

Using a Replacer Function

A replacer allows you to control which keys are included in the string.

let user = { name: "Vicky", age: 28, password: "secret" };

let jsonString = JSON.stringify(user, (key, value) => {
  if (key === "password") return undefined; // Exclude password
  return value;
});

console.log(jsonString);

Output:

{"name":"Vicky","age":28}

The password key is excluded from the string. This is useful for security purposes.

Real-World Example: Saving Data in Local Storage

Local storage can only store strings. So if you want to save an object:

let user = { name: "Vicky", age: 28, skills: ["HTML","CSS","JS"] };

// Convert to JSON string
localStorage.setItem("userData", JSON.stringify(user));

// Retrieve and parse later
let storedUser = JSON.parse(localStorage.getItem("userData"));
console.log(storedUser.name); // Output: Vicky

This demonstrates how JSON.stringify() and JSON.parse() work together in real-world applications.

Notes on JSON.stringify()

  1. Functions are ignored

let obj = { name: "Vicky", greet: () => "Hello" };
console.log(JSON.stringify(obj)); // Output: {"name":"Vicky"}
  1. Undefined values are ignored

let obj = { name: "Vicky", age: undefined };
console.log(JSON.stringify(obj)); // Output: {"name":"Vicky"}
  1. Symbols are ignored

let obj = { id: Symbol("id") };
console.log(JSON.stringify(obj)); // Output: {}
  1. Use replacer and space parameters for filtering and pretty printing.

Summary of the Tutorial

  • JSON.stringify() converts JavaScript objects or arrays into JSON strings.

  • Necessary when sending data to servers or storing in text-based storage.

  • Supports optional replacer and space parameters for filtering and formatting.

  • Functions, undefined values, and symbols are ignored during stringification.

  • Works with arrays, nested objects, and complex structures.

Mastering JSON.stringify() allows you to efficiently send and store data in web applications, completing the core skills for working with JSON in JavaScript.


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 };

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