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.
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.
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).
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.
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.
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.
// 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 Type | In Object | In Array | Standalone |
|---|---|---|---|
| undefined | Omitted | null | undefined (not string) |
| Function | Omitted | null | undefined (not string) |
| Symbol | Omitted | null | undefined (not string) |
| NaN | null | null | null |
| Infinity | null | null | null |
| Date | toJSON() string | toJSON() string | toJSON() string |