What does the JSON.stringify() method do to an object?

👨‍💻 Frontend Developer 🟡 Often Asked 🎚️ Medium
#JavaScript #Objects #JS Basics

Brief Answer

JSON.stringify() converts a JavaScript object to a JSON string. This is needed for sending data to server, saving to localStorage, or transferring between parts of application. The method ignores functions, symbols, and undefined.


Full Answer

JSON.stringify() is a method for turning objects into strings. It’s often used when working with server and data storage.

What the Method Does

Converts object to JSON format string:

const user = { name: 'John', age: 25 };
const json = JSON.stringify(user);
// Result: '{"name":"John","age":25}'

Simple Examples

Regular Object

const obj = { a: 1, b: 'text' };
JSON.stringify(obj);
// '{"a":1,"b":"text"}'

Array

const arr = [1, 2, 'three'];
JSON.stringify(arr);
// '[1,2,"three"]'

What Doesn’t Convert

Functions

const obj = { method: () => {} };
JSON.stringify(obj);
// '{}'

Symbols

const obj = { sym: Symbol('test') };
JSON.stringify(obj);
// '{}'

Undefined

const obj = { value: undefined };
JSON.stringify(obj);
// '{}'

Practical Application

Saving to localStorage

const user = { name: 'John', age: 25 };
localStorage.setItem('user', JSON.stringify(user));

Sending to Server

const data = { message: 'Hello' };
fetch('/api/send', {
  method: 'POST',
  body: JSON.stringify(data)
});

Important Points

1. Circular References

const obj = { name: 'John' };
obj.self = obj; // Circular reference
// JSON.stringify(obj); // Error!

2. Property Order

const obj = { b: 2, a: 1 };
JSON.stringify(obj);
// '{"b":2,"a":1}' - order preserved

Common Mistakes

1. Trying to Save Functions

// ❌ Think functions will be saved
const config = { 
  handler: () => console.log('click') 
};
const saved = JSON.stringify(config);
// saved = '{}' - function lost!
 
// ✅ Save only data
const config = { 
  action: 'click' // action type
};

2. Circular References

// ❌ Will be error
const obj = { name: 'John' };
obj.parent = obj;
// JSON.stringify(obj); // TypeError
 
// ✅ Remove circular references before saving

Simple Rules

  1. For data — converts objects and arrays
  2. Ignores functions — they are lost
  3. Ignores symbols and undefined — also lost
  4. No cycles — will be error
  5. Order preserved — as in original object

JSON.stringify() is a simple way to turn objects into strings for data transfer. Main thing to remember is that not everything can be converted.


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪