Home > Mobile >  Merge multiple JSON files together programmatically, javascript
Merge multiple JSON files together programmatically, javascript

Time:10-21

I am trying to read a directory, use a foreach loop to get the file contents of multiple JSON files, append them together and write them into one file. The bottom code does the job but it does not format the final JSON file correctly as it copies the extra { }'s and does not include commas. Is there a way to format the final output file into correct JSON?

I know you can copy objects into one with the below notation, but I wasn't sure how to do that with multiple files.

object= {"test":"test"}
data={"test2":"test2"}
object={...object, ...data}

let files= fs.readdirSync("library");
function mergeJson() {
    let data;

    files.forEach(x => {
        data = fs.readFileSync(`./library/${x}`);
        let finalData = JSON.parse(data); 

        if(data){
            fs.writeFileSync(`combine.json`, JSON.stringify(finalData), { flag: 'a' }); 
        }
    });
}

CodePudding user response:

I think this could be a possible solution:

const fs = require("fs");

let files = fs.readdirSync("library");

function mergeJson() {
  const output = files.reduce((acum, current) => {
    data = fs.readFileSync(`./library/${current}`);
    const newData = JSON.parse(data);

    return {
      ...acum,
      ...newData,
    };
  }, {});

  if (output) {
    fs.writeFileSync(`combine.json`, JSON.stringify(output), { flag: "a" });
  }
}

mergeJson();
  • Related