How to use replacer with JSON.stringify()

Mudaser Ali
1 min readOct 27, 2019

We use JSON.stringify () to convert a JSON object into string i.e.,

var foo = {
foundation: 'medium',
purpose: 'share stories',
owner: 'SM@K',
hobbies: ['coding', 'photography', 'eating', 'play games']
};
JSON.stringify(foo);// "{"foundation":"medium","purpose":"share stories","owner":"SM@K","hobbies":["coding","photography","eating","play games"]}"

What if we have to stringify only two properties ‘foundation’ & ‘owner’?

Replacer parameter

there is nice but unknown feature of JSON.stringify(), which is second parameter;

The replacer parameter can be either a function or an array.

Array example

var foo = {
foundation: 'medium',
purpose: 'share stories',
owner: 'SM@K',
hobbies: ['coding', 'photography', 'eating', 'play games']
};
JSON.stringify(foo, ['foundation', 'owner']);// "{"foundation":"medium","owner":"SM@K"}

Function Example

Suppose your JSON object contains a Set property

var foo = {
foundation: 'medium',
purpose: 'share stories',
owner: 'SM@K',
hobbies: new Set(['coding', 'photography', 'eating', 'play games'])
};
JSON.stringify(foo);// "{"foundation":"medium","purpose":"share stories","owner":"SM@K","hobbies":{}}"//hobbies = {} ??

so we can resolve this issue by using replacer argument

var foo = {
foundation: 'medium',
purpose: 'share stories',
owner: 'SM@K',
hobbies: new Set(['coding', 'photography', 'eating', 'play games'])
};
JSON.stringify(foo, function(key, value) => {
return value instanceof Set ? [...value] : value;
});
// "{"foundation":"medium","purpose":"share stories","owner":"SM@K","hobbies":["coding","photography","eating","play games"]}"

--

--

Mudaser Ali

{ name: Mudaser Ali aka SMAK, skills: NoBody is pErfect i M nObOdy, passion: {love: [programming, photography]} }