Skip to content

Instantly share code, notes, and snippets.

@iwek
Last active July 5, 2024 14:29
Show Gist options
  • Save iwek/7154578 to your computer and use it in GitHub Desktop.
Save iwek/7154578 to your computer and use it in GitHub Desktop.
CSV to JSON Conversion in JavaScript
//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
}
@php14
Copy link

php14 commented Feb 15, 2019

If i dont have header, how would the first line of code would change?

obj[headers[j]] = currentline[j];

@hassanshaikley
Copy link

hassanshaikley commented Feb 26, 2019

For those unsure how to pass a CSV file the easy way would be to copy paste it into the browser.

  1. Open developer tools / console
  2. Paste the function in
  3. Paste the CSV in like so
var csv = `headerone,headertwo,headerthree
valueone,value2,value3,
...
`
  1. Run the function
csvJSON(csv)

@GuillermoBI
Copy link

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

@Najwa199756
Copy link

@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 ....?

@GuillermoBI
Copy link

@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

Captura de Pantalla 2020-02-18 a la(s) 11 18 42

Captura de Pantalla 2020-02-18 a la(s) 11 20 07

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

@waicampos
Copy link

@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(',')));
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment