Most of the time,
JSON.stringify
is used with the first argument only.
But if we need to fine-tune the replacement process, like to filter out
circular references
, we can use the second argument of
JSON.stringify
let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: [{name: "John"}, {name: "Alice"}],
place: room // meetup references room
};
room.occupiedBy = meetup; // room references meetup
document.write( JSON.stringify(meetup, ['title', 'participants']) );
If we pass an array of properties to it, only these properties will be encoded, so the result will be:
{"title":"Conference","participants":[{},{}]}
As the result shows, the property list is applied to the whole object structure. So the objects in
participants
are empty, because
name
is not in the list.
Let’s include in the list every property except
room.occupiedBy
that would cause the circular reference:
let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: [{name: "John"}, {name: "Alice"}],
place: room // meetup references room
};
room.occupiedBy = meetup; // room references meetup
document.write( JSON.stringify(meetup, ['title', 'participants', 'place', 'name', 'number']) );
The result will be:
{"title":"Conference","participants":[{"name":"John"},{"name":"Alice"}],"place":{"number":23}}
Now everything except
occupiedBy
is serialized. But the list of properties is quite long.
Fortunately, we can use a function instead of an array as the
replacer
.