Home > Software engineering >  How to Parse multiple JSON files to a Same Javascript object?
How to Parse multiple JSON files to a Same Javascript object?

Time:04-12

There is a folder with multiple JSON files that are in the same JSON format. Each file contains the following information: first name, last name, birthday, address, and phone number. Your task is to read all files and parse the data into the same person object. The task is to list all data in any output format you choose, which can be a console as well.

This is my code in NodeJs

import {readdir, readFile} from "fs";
const dir = "./src/json";
const dirAccess = readdir(`${dir}`, (err, files) => {
  files.forEach((file) => {
    const read = readFile(`${dir}/${file}`, "utf8", (err, data) => {
      let p = JSON.parse(data);
      console.log(p);
    });
  });
});

I have my data on 'p', now my question is How can I put all the Parsed JSON data to the Same Person Object?

enter image description here

enter image description here

CodePudding user response:

Create a JSON object outside the forEach function and concatenate all the JSON into that one object.

let jsonconcat = {};   
//then in the loop you do
jsonconcat = {...jsonconcat, p}

Then you can save that as a file or whatever you want to do with the JSON object.

So it should look like:

import {readdir, readFile} from "fs";
const dir = "./src/json";
let jsonconcat = {};   

const dirAccess = readdir(`${dir}`, (err, files) => {
  files.forEach((file) => {
    const read = readFile(`${dir}/${file}`, "utf8", (err, data) => {
      let p = JSON.parse(data);
      jsonconcat = {...jsonconcat, p}
      console.log(p);
    });
  });
});

CodePudding user response:

Found the answer here:

enter image description here

  • Related