Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert CSV data into JSON format using Javascript

I have data in CSV format data and want to convert into JSON format using Javascript.

Following are csv format:

[Test.csv]  id;name;author integer;string;authors:n 1;To Kill an Angry Bird;1  [authors.csv]  id;name integer;string 1;Harper Lee 2;JRR Tolkien 3;William Shakespeare 

I want to get all the books with their authors. So please how can I implement it using Javascript.

like image 982
Pankaj Avatar asked Jan 16 '15 07:01

Pankaj


2 Answers

The below should work for you.

All credit to http://techslides.com/convert-csv-to-json-in-javascript

//var csv is the CSV file with headers function csvJSON(csv){    var lines=csv.split("\n");    var result = [];    // NOTE: If your columns contain commas in their values, you'll need   // to deal with those before doing the next step    // (you might convert them to &&& or something, then covert them back later)   // jsfiddle showing the issue https://jsfiddle.net/   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 } 
like image 102
Wesley Smith Avatar answered Sep 25 '22 18:09

Wesley Smith


I would check out out PapaParse. They have a file called papaparse.min.js that you can drop into your project if need be. PapaParse has no dependencies.

I have used it myself and can verify it works, is convenient, and is well-documented.

like image 44
mareoraft Avatar answered Sep 22 '22 18:09

mareoraft