using JSON.stringify() with values that are not JSON safe
The .toJSON()
method can be defined on an object to be use to transform the object when running JSON.stringify()
.
JavaScript
const includesUnsafeJSON = {
favoriteWater: undefined,
favoriteColors: ['red', 'green', 'blue'],
multiplyByTwo(number) {
return number * 2;
}
};
includesUnsafeJSON.toJSON = function () {
return {
...this
};
};
JSON.stringify(includesUnsafeJSON);
// '{"favoriteColors":["red","green","blue"]}'
An optional second argument can be passed in to tell JSON.stringify()
what properties to keep.
If an array is passed in it will only include the properties with the key values in the array.
JavaScript
const food = {
fruits: ['apples', 'oranges'],
vegetables: ['carrots', 'potatoes'],
colors: ['red', 'green', 'blue']
};
JSON.stringify(food, ['fruits', 'vegetables']);
// '{"fruits":["apples","oranges"],"vegetables":["carrots","potatoes"]}'
If a function is passed in
- it will only include the properties that the function returned
- If you don’t want to include a property return
undefined
, function
or symbol
JavaScript
const food = {
fruits: ['apples', 'oranges'],
vegetables: ['carrots', 'potatoes'],
colors: ['red', 'green', 'blue'],
numbers: [1, 2, 3, 4]
};
JSON.stringify(food, (key, value) => {
if (key === 'numbers') {
return undefined;
}
if (key !== 'colors') {
return value;
}
});
// '{"fruits":["apples","oranges"],"vegetables":["carrots","potatoes"]}'