Hoisting explanation with best 5 example in java script – datainflow
Convert csv data to json
Today I am going to discuss on a topic.Its a very good topic.We can convert csv data to json in php very easily.But while we are going to perform this action in javascript . how can we do this? As you know csv are widely used in application to upload bulk record in a web application.JSON is also a most famous.So we are going to implement csv to json converter using javascript.
First, declare a function which get the csv file.
var apipath = "YourFile.csv"; //This will be the api url var mycsvproduct = []; $.ajax({ url : apipath, type : "get", dataType : "text", success : function(data){ var alldata = convertToJson(data); if(alldata.watchimg.length >0) $(alldata.watchimg).each(function(i){ mycsvproduct.push(alldata.watchimg[i]); }); } });
Then create a function which will convert the data to json. Suppose you have the csv header like heading1, heading2, heading3, heading4.
function convertToJson(allText){ var allTextLines = allText.split(/\r\n|\n/); var headers = allTextLines[0].split(','); var allcsvdata = { watchimg : [] }; for (var i = 1; i < allTextLines.length; i++) { var data = allTextLines[i].split(','); if (data.length == headers.length) { allcsvdata.watchimg.push({ "heading1" : data[0], "heading2" : data[1], "heading3" : data[2], "heading4" : data[3] }); }
That’s all.If you have any query please comment on this post.If you like this post please share it.
Related posts