【问题标题】:NodeJS Replace all values of a defined key in a json fileNodeJS替换json文件中定义键的所有值
【发布时间】:2021-11-12 15:42:35
【问题描述】:

我试图从这个出发:

{
   "Level":"A",
   "Group LVL2":{
      "Level":"B",
      "Group LVL3":{
         "Level":"C"
}}}

到这里

{
   "Level":"C",
   "Group LVL2":{
      "Level":"C",
      "Group LVL3":{
         "Level":"C"
}}}

所以我基本上想将 json 键的所有值替换为相同的值。 这是我正在使用的代码的部分

const fs = require('fs');
const fileName = './' + (Profile) + ".json";
const file = require(fileName);
const key = (Root);
file[Root] = (Value);

fs.writeFile(fileName, JSON.stringify(file, null, 2), function writeJSON(error) {
if (error) return console.log(error);

但它只替换了第一个json组/行的Level Value:

{
   "Level":"THIS WILL BE REPLACED",
   "Group LVL2":{
      "Level":"THIS WILL NOT BE REPLACED",
      "Group LVL3":{
         "Level":"THIS WILL NOT BE REPLACED"
      }
   }
}

希望我能找到解决方案,我指望你! (网上似乎没有任何适合初学者的解决方案)

【问题讨论】:

    标签: node.js json


    【解决方案1】:

    以下是此类问题的通用解决方案,也许您可​​以根据您的问题使其更有效。 它循环遍历作为嵌套对象本身的对象的所有键,对 json 中的每个对象进行递归并更新“级别”键。

    function replaceValues(obj) {
        if(obj.hasOwnProperty(key))
            obj[key] = value;
        for (let property of Object.keys(obj)) {    
            if (typeof(obj[property]) === "object") {
               replaceValues(obj[property]);
            }
        }
    }
    

    根据您使用 Value = "D" 提供的数据进行测试

    {
      "Level": "D",
      "Group LVL2": {
        "Level": "D",
        "Group LVL3": {
          "Level": "D"
        }
      }
    }
    

    【讨论】:

    • 绝对传奇! replaceValues(file) fs.writeFileSync(fileName, JSON.stringify(file, null, 2)) 最后
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多