如何将替换功能与JSON Stringify一起使用? [英] How Do I Use The Replacer Function With JSON Stringify?
本文介绍了如何将替换功能与JSON Stringify一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试使用
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使我更加困惑.
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.
推荐答案
replacer函数需要一个键和一个值(当它通过对象及其子对象时),并期望返回一个新值(字符串类型) ),它将替换原始值.如果返回undefined
,则在结果字符串中将省略整个键/值对.
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.
示例:
- 记录传递给replacer函数的所有键值对:
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);
- 将字符串
" - altered"
添加到所有字符串值:
- 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));
- 忽略所有数字类型的值:
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));
这篇关于如何将替换功能与JSON Stringify一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文