fork download
  1. /**
  2.  * CSVからJsonを作成する
  3.  * @param {String} csv
  4.  * @return {Json}
  5.  */
  6. const generateCsvToJson = (csv) =>
  7. {
  8. const csvLineList = csv.split('\n');
  9. const columnNameList = [];
  10. const resultArray = [];
  11. for (const [index, line] of csvLineList.entries()) {
  12. if (!line || !line.trim()) {
  13. continue;
  14. }
  15. const columnList = line.split(',');
  16. if (index === 0) {
  17. for (const column of columnList) {
  18. columnNameList.push(column);
  19. }
  20. continue;
  21. }
  22.  
  23. const node = {};
  24. for (const [columnIndex, column] of columnList.entries()) {
  25. node[columnNameList[columnIndex]] = column;
  26. }
  27.  
  28. resultArray.push(node);
  29. }
  30.  
  31. return resultArray;
  32. }
  33.  
  34. const x = "receive_date,shipped_date,pref_code,shipping_code\r\n2022-08-01 11:00:00,2022-08-02 16:35:00,1,e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\r\n2022-08-03 15:00:00,2022-08-04 18:29:00,2,60303ae22b998861bce3b28f33eec1be758a213c86c93c076dbe9f558c11c752\r\n";
  35.  
  36. const json = generateCsvToJson(x);
  37. console.log(json);
  38.  
  39. console.log(json[0]['shipping_code']);
  40.  
Success #stdin #stdout 0.03s 18920KB
stdin
Standard input is empty
stdout
[object Object],[object Object]
undefined