【问题标题】:How Do I Use The Replacer Function With JSON Stringify?如何在 JSON Stringify 中使用 Replacer 函数?
【发布时间】:2018-04-03 01:33:57
【问题描述】:

我一直在尝试使用

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 让我更加困惑。

【问题讨论】:

  • 你想用替换器做什么?
  • 我正在尝试将名为“logchannel”的设置中的字符串替换为我告诉它更改为@Reedzev_
  • 你的sn-p代码有问题

标签: javascript json node.js fs


【解决方案1】:

settings 是一个对象,而不是一个文件名。

我正在尝试将名为“logchannel”的设置中的字符串替换为我告诉它更改为的任何内容

const fs = require("fs");
var settings = require("./serversettings.json");
settings.logchannel = "foo"; //specify value of logchannel here
fs.writeFileSync("./serversettings.json", JSON.stringify(settings));

【讨论】:

    【解决方案2】:

    replacer 函数接受一个键和一个值(当它通过对象及其子对象时),并期望返回一个新值(字符串类型)来替换原始值。如果返回undefined,则在结果字符串中省略整个键值对。

    示例:

    1. 记录所有传递给替换函数的键值对:

    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);
    1. 将字符串" - altered" 添加到所有字符串值中:

    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));
    1. 省略所有类型 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));

    【讨论】:

      猜你喜欢
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 2015-03-10
      • 2013-12-27
      • 2016-05-15
      • 1970-01-01
      相关资源
      最近更新 更多