Convert uploaded csv into Json object in node js | CSV to JSON in JavaScript

There are many libraries which we can used to perform this task. But some time we do not want to use library in that case we have to use pure javascript to perform this task.

function csvToJson(csv_data, delimeter=",") {
  console.log(csv_data)
	var lines = csv_data.trim().split(/\r\n|\n/);
	var result = [];
	var headers = lines[0].split(delimeter);
	for (var i = 1; i < lines.length; i++) {
		var obj = {};
		var currentline = lines[i].split(delimeter);
		for (var j = 0; j < headers.length; j++) {
			obj[headers[j]] = currentline[j];
		}
		result.push(obj);
	}
	return result;
}

Example:

let csvdata = `name,age,location,country
anil,32,delhi,india
lina,31,romania,Africa
ani, 26, ukrain, ukrain

`
csvToJson(csvdata);

//Output
[{name:"anil", age:"32", location:"delhi", country:"india"}]

Leave a Reply