Search code examples
javascriptnode.jsarraysjsonnodes

save json object in there provided json file using javascript/ node js


let dataObj={
 print:{
  us:{
  "2343192u4":{
     id:"01",
     name:"linux file",
     location:"System config"
    },
   "23438ufsdjh8":{
     id:"02",
     name:"windows file",
     location:"System config"
    },
   },
   uk:{
    "23438ufsdjh8":{
     id:"01",
     name:"windows",
     location:"System"
    },
  }
   
 },
 hardware:{
  ja:{
   "9058t05":{
     no:"ct-01",
     refrence:"down-tPO-01"
    }
  }
 }
};


let folderName=[{
  filepath:"print"
 },
 {
  filepath:"hardware"
 },
 {
  filepath:"stack"
 },
 {
  filepath:"backupdir"
 },
];

let cont = {
  "45434dsdfsfv": {
    name: "us",
  },
  "4wer23434": {
    name: "uk",
  },
  "6vfkn23421": {
    name: "ja",
  },
  "9dnfjkn23e": {
    name: "ru",
  },
};


Object.values(cont).map((i) =>{
for (const [key, values] of Object.entries(dataObj)) {
            for (const [localeKey, localeValues] of Object.entries(values)) {
              console.log(localeValues);
             // fs.writeFile(path.join(__dirname,key,`${i.name}.json`), JSON.stringify(localeValues, null, 4)
            }
          }
});

I am trying to fetch key from the obj JSON object and compare it with the Array filepath so I can push the value in created json file

here by using fs I am trying to create folder which I got from the array

fs.writeFile(path.join(__dirname,file.filepath,`${cont.name}.json`));

by which I created folder and file with the name which are present inside the cont json and trying to put like this

print/us.json

{
   "2343192u4":{
     id:"01",
     name:"linux file",
     location:"System config"
    },
   "23438ufsdjh8":{
     id:"02",
     name:"windows file",
     location:"System config"
   }
 }

print/uk.json

{
  "23438ufsdjh8":{
     id:"01",
     name:"windows",
     location:"System"
    },
}

hardware/ja.json

{
  "9058t05":{
     no:"ct-01",
     refrence:"down-tPO-01"
    }
}

and so on ...

but the problem is when I do this I am not able to save data in there respective json file I am getting same output in every json file

print/us.json

{
   "2343192u4":{
     id:"01",
     name:"linux file",
     location:"System config"
    },
   "23438ufsdjh8":{
     id:"02",
     name:"windows file",
     location:"System config"
   }
 }

print/uk.json

{
   "2343192u4":{
     id:"01",
     name:"linux file",
     location:"System config"
    },
   "23438ufsdjh8":{
     id:"02",
     name:"windows file",
     location:"System config"
   }
 }

and so on ...

here print hardware stack backupdir always get changed and there are multiple more files as this is system random generated name that why I have to compare and the key from object and make a directory of this name

how can I push them in different different folder with there respective value


Solution

  • Cause:

    As per you following codebase

    Object.values(cont).map((i) =>{
    for (const [key, values] of Object.entries(dataObj)) {
                for (const [localeKey, localeValues] of Object.entries(values)) {
                  console.log(localeValues);
                 // fs.writeFile(path.join(__dirname,key,`${i.name}.json`), JSON.stringify(localeValues, null, 4)
                }
              }
    });
    

    You are looping throgh cont variable and inside the loop you are iterating over the dataObj and values object.

    The problem is you are not asserting the i variable (item of value of cont ) with localKey. Since you are using i variable in the fileName. For all localeKey-localeValue pair, the file name would be same.

    So, according to your codebase following would be the flow of execution

    cont = "us"
        dataObj.hardWare.ja -> write to "/hardware/us.json"
        dataObj.print.uk -> write to "/print/us.json"
        dataObj.print.us -> write to "/print/us.json"
    cont = "uk"
        dataObj.hardWare.ja -> write to "/hardware/uk.json"
        dataObj.print.uk -> write to "/print/uk.json"
        dataObj.print.us -> write to "/print/uk.json"
    cont = "ja"
        dataObj.hardWare.ja -> write to "/hardware/ja.json"
        dataObj.print.uk -> write to "/print/ja.json"
        dataObj.print.us -> write to "/print/ja.json"
    cont = "ru" 
        dataObj.hardWare.ja -> write to "/hardware/ru.json"
        dataObj.print.uk -> write to "/print/ru.json"
        dataObj.print.us -> write to "/print/ru.json"
    

    (NOTE: since the object keys are sorted, the hardware would processed before print. Similarly, print.uk would be processed before print.us.

    Now here, since the dataObj.print.us is processed at the end, all the files would have the dataObj.print.us data.

    Fix: To fix this, you can have something as follow:

    Object.values(cont).map((i) =>{
        for (const [key, values] of Object.entries(dataObj)) {
            for (const [localeKey, localeValues] of Object.entries(values)) {
                if (i.name === localeKey) {
                    // Create directory
                    fs.mkdir(path.join(__dirname, key), { recursive: true }, (err) => {
                        if (err) throw err;
                    });
    
                    // Write data
                    fs.writeFile(path.join(__dirname,key,`${i.name}.json`), JSON.stringify(localeValues, null, 4), (err) => {
                        if (err) {
                            console.error(err)
                        }
                    })
                }
            }
        }
    });
    

    Full code as follow:

    const path = require('path')
    const fs=require('fs')
    
    let dataObj={
        print:{
            us:{
                "2343192u4":{
                    id:"01",
                    name:"linux file",
                    location:"System config"
                },
                "23438ufsdjh8":{
                    id:"02",
                    name:"windows file",
                    location:"System config"
                },
            },
            uk:{
                "23438ufsdjh8":{
                    id:"01",
                    name:"windows",
                    location:"System"
                },
            }
    
        },
        hardware:{
            ja:{
                "9058t05":{
                    no:"ct-01",
                    refrence:"down-tPO-01"
                }
            }
        }
    };
    
    
    let folderName=[{
        filepath:"print"
    },
    {
        filepath:"hardware"
    },
    {
        filepath:"stack"
    },
    {
        filepath:"backupdir"
    },
    ];
    
    let cont = {
        "45434dsdfsfv": {
            name: "us",
        },
        "4wer23434": {
            name: "uk",
        },
        "6vfkn23421": {
            name: "ja",
        },
        "9dnfjkn23e": {
            name: "ru",
        },
    };
    
    
    Object.values(cont).map((i) =>{
        for (const [key, values] of Object.entries(dataObj)) {
            for (const [localeKey, localeValues] of Object.entries(values)) {
                if (i.name === localeKey) {
                    // Create directory
                    fs.mkdir(path.join(__dirname, key), { recursive: true }, (err) => {
                        if (err) throw err;
                    });
    
                    // Write data
                    fs.writeFile(path.join(__dirname,key,`${i.name}.json`), JSON.stringify(localeValues, null, 4), (err) => {
                        if (err) {
                            console.error(err)
                        }
                    })
                }
            }
        }
    });