返回
揭秘 JSON.stringify() 的第二个参数:replacer
前端
2023-10-26 04:06:38
在 JavaScript 中,JSON.stringify() 是一个非常有用的函数,它可以将 JavaScript 对象转换为 JSON 字符串。这对于数据传输和存储非常有用。但是,你可能不知道 JSON.stringify() 还有第二个参数,叫做 replacer。这个参数可以让你自定义 JSON 字符串的输出结果。
JSON.stringify() 的语法如下:
JSON.stringify(value, replacer, space)
其中:
- value 是要转换的 JavaScript 对象。
- replacer 是一个可选的参数,它是一个函数,可以自定义 JSON 字符串的输出结果。
- space 是一个可选的参数,它指定 JSON 字符串的缩进量。
replacer 函数的语法如下:
function replacer(key, value)
其中:
- key 是对象的键。
- value 是对象的键对应的值。
replacer 函数可以返回以下几种值:
- undefined:不输出该键值对。
- null:输出该键值对,但将值设置为 null。
- 其他值:输出该键值对,并使用返回的值作为该键对应的值。
现在,我们来看一些 replacer 函数的示例。
示例 1:忽略某些键值对
const obj = {
name: 'John',
age: 30,
salary: 10000
};
const replacer = (key, value) => {
if (key === 'salary') {
return undefined;
}
return value;
};
const jsonString = JSON.stringify(obj, replacer);
console.log(jsonString);
输出结果:
{"name":"John","age":30}
在这个示例中,replacer 函数返回 undefined,表示不输出 salary 键值对。因此,JSON 字符串中不包含 salary 键值对。
示例 2:将某些值设置为 null
const obj = {
name: 'John',
age: 30,
salary: 10000
};
const replacer = (key, value) => {
if (key === 'salary') {
return null;
}
return value;
};
const jsonString = JSON.stringify(obj, replacer);
console.log(jsonString);
输出结果:
{"name":"John","age":30,"salary":null}
在这个示例中,replacer 函数返回 null,表示将 salary 的值设置为 null。因此,JSON 字符串中 salary 的值为 null。
示例 3:自定义值的输出格式
const obj = {
name: 'John',
age: 30,
salary: 10000
};
const replacer = (key, value) => {
if (key === 'salary') {
return 'const obj = {
name: 'John',
age: 30,
salary: 10000
};
const replacer = (key, value) => {
if (key === 'salary') {
return '$' + value;
}
return value;
};
const jsonString = JSON.stringify(obj, replacer);
console.log(jsonString);
#x27; + value;
}
return value;
};
const jsonString = JSON.stringify(obj, replacer);
console.log(jsonString);
输出结果:
{"name":"John","age":30,"salary":"$10000"}
在这个示例中,replacer 函数返回 '$' + value,表示将 salary 的值转换为 "$10000"。因此,JSON 字符串中 salary 的值为 "$10000"。
示例 4:处理循环引用
const obj = {
name: 'John',
age: 30,
salary: 10000,
self: obj
};
const replacer = (key, value) => {
if (key === 'self') {
return '[Circular reference]';
}
return value;
};
const jsonString = JSON.stringify(obj, replacer);
console.log(jsonString);
输出结果:
{"name":"John","age":30,"salary":10000,"self":"[Circular reference]"}
在这个示例中,obj 对象包含一个指向自身