我一直在尝试使用
const fs = require("fs");
const settings = require("./serversettings.json")
let reason = args.join(' ');
function replacer(key, value) {
return reason;
}
fs.writeFileSync(settings, JSON.stringify(settings.logchannel, replacer))
在我看来,它不起作用,所以我试图弄清楚替换器是如何工作的,因为 MDN 让我更加困惑。
最佳答案
replacer 函数采用一个键和一个值(当它传递对象及其子对象时),并预计返回一个新值(字符串类型)来替换原始值。如果返回 undefined
,则结果字符串中将省略整个键值对。
示例:
- 记录传递给替换函数的所有键值对:
var obj = {
"a": "textA",
"sub": {
"b": "textB"
}
};
var logNum = 1;
function replacer(key, value) {
console.log("--------------------------");
console.log("Log number: #" + logNum++);
console.log("Key: " + key);
console.log("Value:", value);
return value; // return the value as it is so we won't interupt JSON.stringify
}
JSON.stringify(obj, replacer);
- 将字符串
"- alter"
添加到所有字符串值:
var obj = {
"a": "textA",
"sub": {
"b": "textB"
}
};
function replacer(key, value) {
if(typeof value === "string") // if the value of type string
return value + " - altered"; // then append " - altered" to it
return value; // otherwise leave it as it is
}
console.log(JSON.stringify(obj, replacer, 4));
- 省略所有数字类型的值:
var obj = {
"a": "textA",
"age": 15,
"sub": {
"b": "textB",
"age": 25
}
};
function replacer(key, value) {
if(typeof value === "number") // if the type of this value is number
return undefined; // then return undefined so JSON.stringify will omitt it
return value; // otherwise return the value as it is
}
console.log(JSON.stringify(obj, replacer, 4));
关于javascript - 如何将 Replacer 函数与 JSON Stringify 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46873496/