javascript - 如何将 Replacer 函数与 JSON Stringify 结合使用?

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

最佳答案

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

  • 将字符串 "- alter" 添加到所有字符串值:
  • 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));

    关于javascript - 如何将 Replacer 函数与 JSON Stringify 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46873496/

    相关文章:

    json - 如何将 HAL JSON 数据转换为 jQuery DataTables 的 JSON 数组

    javascript - 如何将 id IS NOT NULL 与转义变量 ??/?

    javascript - 在 C++ 服务器中处理使用 WebRTC (Socket.IO) 捕获的视频数据

    javascript - 在 jQuery UI Sortable 之后更新 CollectionView 内容的最佳方式?

    PHP在while循环中向数组添加列和条目

    javascript - 使用 express 在 node.js 中编写登录

    javascript - 数组 "property lists"叫什么,它们与简单对象有何不同?

    javascript - Chart.js 的垂直网格线问题

    javascript - 更新 DIV 并在 1 秒后使用 setTimeout 再次清空它

    json - 在 Elm 中解析 JSON