0

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

Adnan Sparrow
  • 25
  • 2
  • 8
  • This is easy! Make jsonData and array; and then do array.push(p); Ill update my answer. The problem is that without the context of your JSON data added in the answer your question could be taken as wanting a single JSON object with all the data. But what you want is a JSON array with all the objects of all the files. – Obsidianlab Apr 12 '22 at 08:51

2 Answers2

0

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);
    });
  });
});
Obsidianlab
  • 667
  • 1
  • 4
  • 24
0

Found the answer here:

JavaScript function return is empty after file read

How to make fs.readFile async await?

readdir and readFile are async so you need to let the code wait for the process to be done.

import fs, { readdir, readFile } from 'fs';
import path from 'path';
const dir = './src/json';
let jsonData = [];

async function readingDirectory(directory) {
  const fileNames = await fs.promises.readdir(directory);
  for (let file of fileNames) {
    const absolutePath = path.join(directory, file);

    const data = await fs.promises.readFile(absolutePath);
    let p = JSON.parse(data);
    console.log(absolutePath, p);
    jsonData.push(p);
  }
}

readingDirectory(dir)
  .then(() => {
    console.log(jsonData);
  })
  .catch((err) => {
    console.log(err);
  });

enter image description here

Obsidianlab
  • 667
  • 1
  • 4
  • 24