问题
I've been trying to use
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))
It seems like to me that it doesn't work, so I'm trying to figure out how replacers work as MDN made me even more confused.
回答1:
The replacer function takes a key and a value (as it passes through the object and its sub objects) and is expected to return a new value (of type string) that will replace the original value. If undefined
is returned then the whole key-value pair is omitted in the resulting string.
Examples:
- Log all key-value pairs passed to the replacer function:
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);
- Add the string
" - altered"
to all string values:
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));
- Omitt all values of type number:
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));
回答2:
settings
is an object, not a filename.
I'm trying to replace the string in the settings named as "logchannel" to whatever I tell it to change it to
const fs = require("fs");
var settings = require("./serversettings.json");
settings.logchannel = "foo"; //specify value of logchannel here
fs.writeFileSync("./serversettings.json", JSON.stringify(settings));
来源:https://stackoverflow.com/questions/46873496/how-do-i-use-the-replacer-function-with-json-stringify