1
Reply

how to convert csv file to json format in angular 4?

Karthik Kumar

Karthik Kumar

Nov 8 2017 8:09 AM
766
i need to select one csv file and convert it in to json list.for that i wrote a javascript function but its not giving the exat json list
 
this is the js method
  1. <input type="file" accept=".csv" (change)="convertFile($event)" />  
  2.   
  3. convertFile(csv: any) {  
  4.   
  5. this.fileReaded = csv.target.files[0];  
  6.   
  7. let reader: FileReader = new FileReader();  
  8. reader.readAsText(this.fileReaded);  
  9.   
  10. reader.onload = (e) => {  
  11. let csv: string = reader.result;  
  12. let allTextLines = csv.split(/\r|\n|\r/);  
  13. let headers = allTextLines[0].split(',');  
  14. let lines = [];  
  15.   
  16. for (let i = 0; i < allTextLines.length; i++) {  
  17. // split content based on comma  
  18. let data = allTextLines[i].split(',');  
  19. if (data.length === headers.length) {  
  20. let tarr = [];  
  21. for (let j = 0; j < headers.length; j++) {  
  22. tarr.push(data[j]);  
  23. }  
  24.   
  25. // log each row to see output  
  26. console.log(tarr);  
  27. lines.push(tarr);  
  28. }  
  29. }  
  30. // all rows in the csv file  
  31. console.log(">>>>>>>>>>>>>>>>>", lines);  
  32. }  
but this is giving o/p like
 
. Array(21)
. 0:(3) ["ONE", "TWO", "THREE"]
. 1:(3) ["9345", "ui: Publishing Start Date and end date should add calendar function", "Committed"]
. 2:(3) ["9339", "gg: The options for default shall be in language table as Y and N", "Approved"]
. 3:(3) ["9295", "URAXR2: A message info is to be added after delete the variable in variable tab ", "bb"]
. 4:(3) ["9276", "bb: Valid error message should be added in Formula tab", "Approved"]
. 5:(3) ["9275", "bb: The spelling of the record is incorrect in…ssage info when deleting record from nntables", "Approved"]
. 6:(3) ["9274", "nn:? The values get blank when edit the record in Group tables tab", "Committed"]
. 7:(3) [
 
i need to get like below
 
[
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
},
{
color: "cyan",
value: "#0ff"
},
]

Answers (1)