Skip to content Skip to sidebar Skip to footer

How Do I Use The Replacer Function With Json Stringify?

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;

Solution 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:

  1. Log all key-value pairs passed to the replacer function:

var obj = {
  "a": "textA",
  "sub": {
    "b": "textB"
  }
};

var logNum = 1;
functionreplacer(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. Add the string " - altered" to all string values:

var obj = {
  "a": "textA",
  "sub": {
    "b": "textB"
  }
};

functionreplacer(key, value) {
  if(typeof value === "string")    // if the value of type stringreturn value + " - altered";   // then append " - altered" to itreturn value;                    // otherwise leave it as it is
}

console.log(JSON.stringify(obj, replacer, 4));
  1. Omitt all values of type number:

var obj = {
  "a": "textA",
  "age": 15,
  "sub": {
    "b": "textB",
    "age": 25
  }
};

functionreplacer(key, value) {
  if(typeof value === "number")    // if the type of this value is numberreturnundefined;              // 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));

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

Post a Comment for "How Do I Use The Replacer Function With Json Stringify?"