Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

486
Visualizações
How to Parse multiple JSON files to a Same Javascript object?

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

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

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);
    });
  });
});
about 4 years ago · Santiago Trujillo Relatório

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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda