JavaScript JSON.stringify()

The JSON.stringify() method converts a JavaScript value (object, array, or primitive) into a JSON string. It is used to serialize data for storage or transmission to a server.

Basic JSON.stringify()

Pass any JavaScript value to JSON.stringify() and it returns the corresponding JSON string representation.

Stringify Basics
const obj = { name: 'Alice', age: 30, active: true };
const json = JSON.stringify(obj);
console.log(json);
console.log(typeof json);

// Arrays
const arr = [1, 'two', true, null];
console.log(JSON.stringify(arr));

// Primitives
console.log(JSON.stringify(42));
console.log(JSON.stringify('hello'));
console.log(JSON.stringify(true));
console.log(JSON.stringify(null));

The Replacer Function

The second parameter of JSON.stringify() is the replacer. It can be a function that transforms values during serialization, or an array that specifies which properties to include.

Replacer as a Function
const user = {
  name: 'Alice',
  password: 'secret123',
  age: 30,
  email: 'alice@example.com'
};

// Replacer function: filter out sensitive data
const safe = JSON.stringify(user, function(key, value) {
  if (key === 'password') {
    return undefined;  // Omit this property
  }
  return value;
});
console.log('Filtered: ' + safe);

// Replacer as array: include only specified keys
const partial = JSON.stringify(user, ['name', 'email']);
console.log('Partial: ' + partial);

The Space Parameter (Pretty Print)

The third parameter controls indentation for readability. You can pass a number (spaces) or a string (custom indentation).

Pretty Printing JSON
const data = {
  name: 'Product',
  price: 29.99,
  tags: ['sale', 'featured'],
  details: {
    weight: '1kg',
    color: 'blue'
  }
};

// Compact (default)
console.log('Compact:');
console.log(JSON.stringify(data));

// Pretty with 2 spaces
console.log('\nPretty (2 spaces):');
console.log(JSON.stringify(data, null, 2));

// Pretty with tab
console.log('\nPretty (tab):');
console.log(JSON.stringify(data, null, '\t'));

The toJSON() Method

If an object has a toJSON() method, JSON.stringify() calls it and uses the return value instead of the object itself. This lets you customize how an object is serialized.

Custom toJSON()
class Temperature {
  constructor(celsius) {
    this.celsius = celsius;
    this.fahrenheit = celsius * 9/5 + 32;
  }

  toJSON() {
    return {
      value: this.celsius,
      unit: 'C',
      display: this.celsius + '°C'
    };
  }
}

const temp = new Temperature(100);
console.log(JSON.stringify(temp, null, 2));

// Date objects have built-in toJSON()
const date = new Date('2024-06-15');
console.log(JSON.stringify({ date: date }));

Handling undefined, Functions, and Symbols

JSON.stringify() handles certain JavaScript values specially: undefined, functions, and symbols are omitted from objects or converted to null in arrays.

Special Values Behavior
const obj = {
  name: 'Test',
  value: undefined,
  method: function() { return 1; },
  symbol: Symbol('id'),
  valid: 'yes'
};

// undefined, functions, symbols are OMITTED from objects
console.log(JSON.stringify(obj));

// In arrays, they become null
const arr = [1, undefined, function(){}, Symbol('x'), 'hello'];
console.log(JSON.stringify(arr));

// Standalone undefined/function returns undefined (not a string)
console.log(JSON.stringify(undefined));
console.log(typeof JSON.stringify(undefined));

Circular References

JSON.stringify() throws a TypeError if the object contains circular references (an object that references itself). You need to handle this manually or use a replacer.

Handling Circular References
// Circular reference example
const obj = { name: 'Circular' };
// obj.self = obj;  // This would cause TypeError

// Safe stringify that handles circular references
function safeStringify(obj) {
  const seen = new Set();
  return JSON.stringify(obj, function(key, value) {
    if (typeof value === 'object' && value !== null) {
      if (seen.has(value)) {
        return '[Circular Reference]';
      }
      seen.add(value);
    }
    return value;
  }, 2);
}

const a = { name: 'A' };
const b = { name: 'B', ref: a };
a.ref = b;  // Circular!

console.log(safeStringify(a));
Value TypeIn ObjectIn ArrayStandalone
undefinedOmittednullundefined (not string)
FunctionOmittednullundefined (not string)
SymbolOmittednullundefined (not string)
NaNnullnullnull
Infinitynullnullnull
DatetoJSON() stringtoJSON() stringtoJSON() string
📝 Note: JSON.stringify() is commonly used to deep clone objects (JSON.parse(JSON.stringify(obj))), but this approach loses functions, undefined values, symbols, and Date objects (converted to strings). For proper deep cloning, use structuredClone() instead.
Exercise:
What happens when JSON.stringify() encounters a function in an object?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.