HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JSON.stringify()

To send data to a web server or store it in LocalStorage, the data must be a string. JSON.stringify() is a built-in method that converts a JavaScript object or array into a JSON-formatted string.


Object Serialization Lab

Observe how a live JavaScript object is converted into a transmission-ready string. Toggle "Pretty Print" to see how whitespace affects readability:

// Stringified output will appear here

Basic Example

Use JSON.stringify() to convert a JavaScript object into a string:

const user = { name: "Alice", age: 25, city: "Paris" };

const myJSON = JSON.stringify(user);

console.log(myJSON); 
// Output: '{"name":"Alice","age":25,"city":"Paris"}'

Handling Arrays

You can also stringify JavaScript arrays. The result will be a string following JSON array syntax (using square brackets).

const colors = ["Red", "Green", "Blue"];

const myJSON = JSON.stringify(colors);

console.log(myJSON); 
// Output: '["Red","Green","Blue"]'

The "Pretty Print" Parameter

By default, JSON.stringify() removes all whitespace to save space. To make the output human-readable, you can pass a third parameter representing the number of spaces to use for indentation.

// Indent with 4 spaces
let str = JSON.stringify(user, null, 4);
Note: The second parameter is an optional replacer function that can be used to filter or transform the object's properties before stringifying.

Special Data Constraints

Just like JSON.parse(), stringify has limitations:

  • Dates: JSON.stringify() will automatically convert Date objects into ISO strings.
  • Functions: JSON.stringify() will remove functions from a JavaScript object.
  • Undefined: Properties with undefined values are also removed.
const obj = { 
    name: "John", 
    age: undefined, 
    greet: function() { return "Hi"; } 
};

console.log(JSON.stringify(obj));
// Output: '{"name":"John"}' (age and greet are gone!)

Key Points to Remember

  • JSON.stringify() converts JS objects to JSON strings.
  • It is essential for sending data to a server via AJAX/Fetch.
  • It is mandatory for saving objects in LocalStorage.
  • Functions and undefined values are stripped out.
  • Dates are converted to ISO strings.
  • Use the 3rd parameter for Indentation (Pretty Printing).