在调用 JSON.stringify()
的时候可以使用第二个参数 replacer
。这个参数接收 function/array
,用来起到选择和筛选属性的作用。如果这个参数给出的是 null
,那么所有属性都会被返回。若参数是函数,则函数的参数分别是 key 和 value。
// function
function replacer(key, value) {
// Filtering out properties
if (typeof value === 'string') {
return undefined;
}
return value;
}
var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
JSON.stringify(foo, replacer); // '{"week":45,"month":7}'
// array
JSON.stringify(foo, ['week', 'month']);
// '{"week":45,"month":7}', only keep "week" and "month" properties
当遇到对象循环引用的时候,这时候使用 JSON.stringify()
会报错。
const obj = { a: 123 }
obj.myself = obj
为解决报错的问题,我们可以使用 replacer 参数来进行过滤。
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(obj, getCircularReplacer()); // '{"a":123}'