Data, Maps, Usability, and Performance

Convert CSV to JSON in JavaScript

Last updated on October 27, 2013 in Uncategorized

CSV to JSON convert

I have been dealing with a lot of CSV and TSV files lately and I am a bit surprised at the lack of support for these formats in jQuery. D3.js supports it out of the box which is awesome but often times I need to convert CSV to JSON without loading D3. You could argue that I should just convert the data into JSON before loading it onto the page, especially since at the end of the day I will need to convert it into a JavaScript object. That is an option, and there are many converters out there, but what about transferring more data over the network? CSV and TSV are always going to be smaller than JSON and I like that, so often times, I actually prefer to load a CSV file into the page and convert it into JSON with JavaScript. Also, a TSV or CSV to JSON conversion function in JavaScript is pretty simple.

The difference between a CSV and TSV is only the separator used in between the value: CSV uses a comma and TSV uses a tab. The difference between CSV or TSV and JSON is that in JSON the key or parameter is repeated in every row or object. There are other differences but they do not matter in terms of conversion between the two formats. One thing that could be an issue is that both CSV and TSV do not need to have headers so we would need to make that a requirement for our conversion function and it makes sense as JSON really needs to know what is the parameter/header name.

Here is my JavaScript function to convert CSV into JSON:

First I take the whole CSV file and split it into an array of lines. Then, I take the first line, which should be the headers, and split that by a comma into an array. Then, I loop through all the lines (skipping the first one) and inside, I loop through the headers and assign the values from each line to the proper object parameters. At this point, you probably want to just return the JavaScript object, but you can also JSON.stringify the result and return the JSON object.

Here is my JavaScript function to convert TSV into JSON:

As you can see, the only difference here is that I am not looking for a comma but for a tab to do the split. Here is a demo that allows you to upload a CSV or TSV and get a JSON file back, all on the client side, a HTML5 CSV or TSV to JSON Converter.

Tags: ,

Facebook Twitter Hacker News Reddit More...