如何使用JSON Stringify的替换器功能?

时间:2017-10-22 11:25:02

标签: javascript json node.js fs

我一直在尝试使用

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

2 个答案:

答案 0 :(得分:1)

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

<强>示例:

  1. 记录传递给replacer功能的所有键值对:
  2. 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"添加到所有字符串值:
    2. 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. 省略所有类型编号的值:
      2. 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));

答案 1 :(得分:0)

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));