This post shows how you can convert a simple CSV file to JSON in JavaScript.
Consider the following sample CSV:
author,title,publishDate Dan Simmons,Hyperion,1989 Douglas Adams,The Hitchhiker's Guide to the Galaxy,1979
The desired JSON output is:
[{"author":"Dan Simmons","title":"Hyperion","publishDate":"1989"},
{"author":"Douglas Adams","title":"The Hitchhiker's Guide to the Galaxy","publishDate":"1979"}]
The following JavaScript function transforms CSV into JSON. (Note that this implementation is quite naive and will not handle quoted fields containing commas!)
function toJson(csvData) {
var lines = csvData.split("\n");
var colNames = lines[0].split(",");
var records=[];
for(var i = 1; i < lines.length; i++) {
var record = {};
var bits = lines[i].split(",");
for (var j = 0 ; j < bits.length ; j++) {
record[colNames[j]] = bits[j];
}
records.push(record);
}
return records;
}
A simple test:
csv="author,title,publishDate\nDan Simmons,Hyperion,1989\nDouglas Adams,The Hitchhiker's Guide to the Galaxy,1979"; json = toJson(csv); console.log(JSON.stringify(json));
To read a CSV file in JavaScript and convert it to JSON:
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "books.csv", true);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
var result = toJson(allText);
console.log(JSON.stringify(result));
}
}
}
rawFile.send(null);
You might also like:
Converting XML to CSV using XSLT 1.0
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.