Export JSON to CSV file using Javascript (in the browser)

Danny Pule
2 min readFeb 8, 2017

--

Update 2017/10/25: A couple of readers have posted in the comments about the flexibility of this code in the following scenarios:

If a field contains the delimiter (e.g. ‘,’)

If a field contains the quote symbol (e.g. ‘“’)

If a field contains a new line symbol (e.g. ‘\n’)

If a field contains non-English characters such as Persian characters etc

I’m sure there are more cases but as this isn’t a fully fledged library I haven’t felt the need to make the code bullet-proof. My suggestion is to test the below code with your source data and if you are sure that it will always have that set of characters, then use the below code for your project.

Recently I needed to create this functionality for a project at work. After searching Stack Overflow, various blogs and npm packages, I couldn’t find a reliable solution from one source that just worked in the browser and didn’t rely on server-side processing of any kind.

I put together my own working version by combining a couple of Stack Overflow answers modifying them slightly to fit most basic use cases. The example in the Gist and Codepen should be fairly easy to modify and add extended functionality if you wanted.

[SOURCE 1] http://stackoverflow.com/questions/11257062/converting-json-object-to-csv-format-in-javascript

[SOURCE 2] http://stackoverflow.com/questions/14964035/how-to-export-javascript-array-info-to-csv-on-client-side

Gist Code Example

Using convertToCSV() and exportCSVFile() from the above Gist, you can easily convert a Javascript array of object to JSON and finally to CSV.

Call the“exportCSVFile(headers, itemsFormatted, fileTitle)” function and insert your own “headers”, “itemsFormatted” and “fileTitle” variables.

Codepen Live Demo

Live demo below or at http://codepen.io/danny_pule/pen/WRgqNx

--

--