-
-
Save iwek/7154578 to your computer and use it in GitHub Desktop.
//var csv is the CSV file with headers | |
function csvJSON(csv){ | |
var lines=csv.split("\n"); | |
var result = []; | |
var headers=lines[0].split(","); | |
for(var i=1;i<lines.length;i++){ | |
var obj = {}; | |
var currentline=lines[i].split(","); | |
for(var j=0;j<headers.length;j++){ | |
obj[headers[j]] = currentline[j]; | |
} | |
result.push(obj); | |
} | |
//return result; //JavaScript object | |
return JSON.stringify(result); //JSON | |
} |
For those unsure how to pass a CSV file the easy way would be to copy paste it into the browser.
- Open developer tools / console
- Paste the function in
- Paste the CSV in like so
var csv = `headerone,headertwo,headerthree
valueone,value2,value3,
...
`
- Run the function
csvJSON(csv)
Add trim to clean whitespaces
`
function csvJSON(csv){var lines=csv.split("\n");
var result = [];
var headers=lines[0].split(",");
headers = headers.map(function(h) {
return h.trim();
});for(var i=1;i<lines.length;i++){
var obj = {}; var currentline=lines[i].split(","); for(var j=0;j<headers.length;j++){ obj[headers[j]] = currentline[j].trim(); } result.push(obj);
}
//return result; //JavaScript object
return JSON.stringify(result); //JSON
}
`
this Method works for me, i have been searching a lot of time, but this partner have a correct answer, thanks.. really
@GillermoBI : plz can uu tell us how can i do to execute the script & run it to see the result , cause i don't see how can i put my file_csv ....?
@GillermoBI : plz can uu tell us how can i do to execute the script & run it to see the result , cause i don't see how can i put my file_csv ....?
@Najwa199756 sure, the script, running in the moment to read a file, from a file input type:
<div class="col-4 col-button">
<button mat-stroked-button color="primary" (click)="fileInput.click()"> <mat-icon>attachment</mat-icon> Cargar</button>
<label for="fileInput"></label>
<input id="fileInput" (change)="onFileSelected($event)" #fileInput type="file" hidden/>
<button mat-stroked-button color="primary" *ngIf="layout" (click)="viewLayout()" matTooltip="ver Layout">
<mat-icon>attach_file</mat-icon>
</button>
</div>
(i use angular 8 for my app), later, when the event fires, i read the file with FileReader and converts as a text:
- some validations for my app it's included
- tempLayout its the result of the csv converted to json,
onFileSelected(event) {
let reader = new FileReader();
if (event.target.files && event.target.files.length > 0) {
let position = event.target.files[0].name.indexOf('.');
if(event.target.files[0].name.substring((position+1), event.target.files[0].name.length) === 'csv'){
reader.readAsText(event.target.files[0]);
reader.onload = (e) => {
const csv: string = reader.result as string;
let tempLayout = this.csvJSON(csv);
tempLayout = this.checkLayout(tempLayout);
if(tempLayout){
if(!this.filterLayout(tempLayout)){
event.target.value = '';
}
} else {
event.target.value = '';
}
}
} else {
this.comunesService.showMessage("debe insertar un archivo con terminacion .csv");
event.target.value = '';
this.layout = undefined;
this.layoutChanged = undefined;
this.openDialog();
}
}
}
later, when some validations it's ok, i use the csv-json converter
csvJSON(csv: string){
let lines=csv.split("\n");
let result = [];
let headers=lines[0].split(",");
let that = this;
headers = headers.map(function(h) {
h = h.toLowerCase();
h = that.camelCase(h);
return h.trim();
});
for(let i=1;i<lines.length;i++){
let obj = {};
let currentline=lines[i].split(",");
for(let j=0;j<headers.length;j++){
if(currentline[j]){
obj[headers[j]] = currentline[j].trim();
} else {
obj[headers[j]] = "";
}
}
result.push(obj);
}
return result;
}
- the output attach in a file for view how is the result
the function to camelcase() and toLowerCase() its only for a format that i use for my info, it's not necessary.
I hope to this info helps you and others that have this same problem, other thing, sorry for mi english, i'm learning it, hehe
@OFRBG I liked this your solution. I suggest just filtering the lines before iteration to eliminate blank lines from the csv file.
const csvToJson = csv => {
const [firstLine, ...lines] = csv.split('\n');
const keys = firstLine.split(',');
// add a filter here
return lines.filter(line => line).map(line => ((values) =>
keys.reduce(
(curr, next, index) => ({
...curr,
[next]: values[index],
}),
{}
)
)(line.split(',')));
};
If i dont have header, how would the first line of code would change?