본문 바로가기

etc

csvToJson 사용해봄

첫번째 코드는 원치 않게 비동기적으로 작동을 했다.

post.json을 쓰기도 전에 읽어버려서 error가 뜬다. 다른 문제로는 post-user_id와 user-id가 같은 것 여러개가 있는 것을 console.log로 확인할 수 있었는데 저장 되는건 하나 밖에 없다.

문제 해결 => 읽는것을 쓰는 것후에 할것 (동기적 함수로 이용), 여러개 post를 저장하는건 배열을 만들어 추가를하고 추가가 끝나면 해당 Id에 post arr를 넣어준다

let csvToJson = require("csvtojson");
const fs = require("fs");
const postCsv = "posts.csv";
const usersCsv = "users.csv";
// CSV ==> json
csvToJson()
  .fromFile(usersCsv)
  .then((jsonObj) => {
    // console.log(jsonObj);
    fs.writeFileSync("result.json", JSON.stringify(jsonObj));
  })
  .catch((err) => {
    console.log(err);
  });
csvToJson()
  .fromFile(postCsv)
  .then((jsonObj) => {
    //console.log(jsonObj);
    fs.writeFileSync("post.json", JSON.stringify(jsonObj));
  })
  .catch((err) => {
    console.log(err);
  });

// JSON READ
const postBuffer = fs.readFileSync("post.json");
const postJson = postBuffer.toString();
const post = JSON.parse(postJson);

const userBuffer = fs.readFileSync("result.json");
const userJson = userBuffer.toString();
const user = JSON.parse(userJson);

// post[i][user_id] == user.id than user.push post[i]
// 한개만 추가됨
// post.forEach((content) => {
//   user.forEach((index, i) => {
//     if (content.user_id == index.id) {
//       console.log(`==========post id${content.user_id}  && userid${index.id}`);
//       user[i].post = content;
//       let postjson = JSON.stringify(user);
//       fs.writeFileSync("result.json", postjson);
//     }
//   });
// });

알게된것 await 는 함수 앞에 쓸 수 있다.

let csv = require("csvtojson");
const fs = require("fs");
const postCsv = "posts.csv";
const usersCsv = "users.csv";
// CSV ==> json
async function csvToJson() {
  await csv()
    .fromFile(usersCsv)
    .then((jsonObj) => {
      // console.log(jsonObj);
      fs.writeFileSync("result.json", JSON.stringify(jsonObj));
    })
    .catch((err) => {
      console.log(err);
    });
  await csv()
    .fromFile(postCsv)
    .then((jsonObj) => {
      //console.log(jsonObj);
      fs.writeFileSync("post.json", JSON.stringify(jsonObj));
    })
    .catch((err) => {
      console.log(err);
    });
}
const readAndWriteFile = async () => {
  await csvToJson();
  // JSON READ
  let userBuffer = fs.readFileSync("result.json");
  let postBuffer = fs.readFileSync("post.json");
  const postJson = postBuffer.toString();
  const post = JSON.parse(postJson);
  const userJson = userBuffer.toString();
  const user = JSON.parse(userJson);
  
  // post[i][user_id] == user.id than user.push post[i]
  user.forEach((index, i) => {
    let arr = [];
    post.forEach((content) => {
      if (content.user_id == index.id) {
        // console.log(`==========post id${content.user_id}  && userid${index.id}`);
        arr.push(content);
      }
    });
    user[i].post = arr;
    let postjson = JSON.stringify(user);
    fs.writeFileSync("result.json", postjson);
  });
  console.dir(user, { depth: null });
};

readAndWriteFile();

'etc' 카테고리의 다른 글

첫 WEB프로젝트 회고 - unic5n🦄 가구이커머스 모델링  (1) 2023.04.15
git - cherry-pick(체리픽)  (0) 2023.03.28
iterm 2 자동완성 &  (0) 2023.03.24
Git 명령어  (0) 2023.03.17
REST&SOAP  (0) 2023.03.15