Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Last active December 25, 2015 15:41
Show Gist options
  • Save softwarespot/c47b25f63c1bddda812a to your computer and use it in GitHub Desktop.
Save softwarespot/c47b25f63c1bddda812a to your computer and use it in GitHub Desktop.
JSON to CSV
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>JSON to CSV</title>
<!--Mobile Specific Metas-->
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<!--Font-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"/>
<!--Stylesheets-->
<style>
/*Body styling*/
body {
font-family: 'Open Sans', sans-serif, Arial;
}
textarea {
height: 200px;
width: 99%;
}
</style>
</head>
<body>
<h1>JSON to CSV</h1>
<p>Convert the following JSON objects to a CSV file</p>
<textarea id="json-to-csv"></textarea>
<br/>
<input type="button" value="Convert to CSV"/>
<!--Scripts-->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
(function (window, $) {
// Cache the jQuery selector objects
var _$convert = $('[type="button"]');
var _$textArea = $('#json-to-csv');
// Register an 'onclick' event handler
_$convert.on('click.json_to_csv', function _onClick() {
var data = _$textArea.val();
var jsonString = _parseAsJSON(data);
var csvString = _jsonToCSV(jsonString);
// URL: http://stackoverflow.com/a/4130939/317 AND http://www.hybridplanet.co.in/tutorial/javascript/how-to-create-csv-or-excel-file-from-json-via-javascript
var uriContent = 'data:text/csv;charset=utf-8,' + window.encodeURIComponent(csvString);
var element = document.createElement('a');
element.href = uriContent;
element.style = 'visibility:hidden';
element.download = 'data.csv';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
});
/**
* Convert a JSON string to a CSV string
*
* @param {string} data JSON string to convert
* @return {string} CSV string converted from a JSON string
*/
function _jsonToCSV(data) {
var array = window.JSON.parse(data);
if (array.length === 0) {
return '';
}
// Create a buffer to store the strings (a lot more efficient than concatenation)
var buffer = [];
var json = array[0];
var key = '';
// Headings
for (key in json) {
// Check if the property belongs to the object
if (!json.hasOwnProperty(key)) {
continue;
}
buffer.push('"');
// Escape any double quotation marks
buffer.push(key.replace(/"/g, '""'));
buffer.push('"');
buffer.push(',');
}
// Pop the last comma
buffer.pop();
// Push a new line character to signify the end of the line
buffer.push('\r\n');
// Values
for (var i = 0, length = array.length; i < length; i++) {
json = array[i];
for (key in json) {
// Check if the property belongs to the object
if (!json.hasOwnProperty(key)) {
continue;
}
buffer.push('"');
var value = json[key];
if (typeof value === 'string' || window.Object.prototype.toString.call(value) === '[object String]') {
value = json[key].replace(/"/g, '""');
}
// Escape any double quotation marks
buffer.push(value);
buffer.push('"');
buffer.push(',');
}
// Pop the last comma
buffer.pop();
// Push a new line character to signify the end of the line
buffer.push('\r\n');
}
return buffer.join('');
}
/**
* Parse to a valid JSON string array, by escaping new line characters with a comma and surround with square brackets
*
* @param {string} data Data to parse as a valid JSON string
* @return {string} Valid JSON string
*/
function _parseAsJSON(data) {
// Coerce as a string
return '[' + ('' + data).replace(/\r\n?|\n/g, ',') + ']';
}
})(this, this.jQuery);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>JSON to CSV</title>
<!--Mobile Specific Metas-->
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<!--Font-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"/>
<!--Stylesheets-->
<style>
/*Body styling*/
body {
font-family: 'Open Sans', sans-serif, Arial;
}
textarea {
height: 200px;
width: 99%;
}
</style>
</head>
<body>
<h1>JSON to CSV</h1>
<p>Convert the following JSON objects to a CSV file</p>
<textarea id="json-to-csv"></textarea>
<br/>
<input type="button" value="Convert to CSV"/>
<!--Scripts-->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
(function (window, $) {
// Cache the jQuery selector objects
var _$convert = $('[type="button"]');
var _$textArea = $('#json-to-csv');
// Register an 'onclick' event handler
_$convert.on('click.json_to_csv', function _onClick() {
var data = _$textArea.val();
var jsonString = _parseAsJSON(data);
var csvString = _jsonToCSV(jsonString);
// URL: http://stackoverflow.com/a/4130939/317 AND http://www.hybridplanet.co.in/tutorial/javascript/how-to-create-csv-or-excel-file-from-json-via-javascript
var uriContent = 'data:text/csv;charset=utf-8,' + window.encodeURIComponent(csvString);
var element = document.createElement('a');
element.href = uriContent;
element.style = 'visibility:hidden';
element.download = 'data.csv';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
});
/**
* Convert a JSON string to a CSV string
*
* @param {string} data JSON string to convert
* @return {string} CSV string converted from a JSON string
*/
function _jsonToCSV(data) {
var array = window.JSON.parse(data);
if (array.length === 0) {
return '';
}
// Create a buffer to store the strings (a lot more efficient than concatenation)
var buffer = [];
var json = array[0];
var key = '';
// Headings
for (key in json) {
// Check if the property belongs to the object
if (!json.hasOwnProperty(key)) {
continue;
}
buffer.push('"');
// Escape any double quotation marks
buffer.push(key.replace(/"/g, '""'));
buffer.push('"');
buffer.push(',');
}
// Pop the last comma
buffer.pop();
// Push a new line character to signify the end of the line
buffer.push('\r\n');
// Values
for (var i = 0, length = array.length; i < length; i++) {
json = array[i];
for (key in json) {
// Check if the property belongs to the object
if (!json.hasOwnProperty(key)) {
continue;
}
buffer.push('"');
var value = json[key];
if (typeof value === 'string' || window.Object.prototype.toString.call(value) === '[object String]') {
value = json[key].replace(/"/g, '""');
}
// Escape any double quotation marks
buffer.push(value);
buffer.push('"');
buffer.push(',');
}
// Pop the last comma
buffer.pop();
// Push a new line character to signify the end of the line
buffer.push('\r\n');
}
return buffer.join('');
}
/**
* Parse to a valid JSON string array, by escaping new line characters with a comma and surround with square brackets
*
* @param {string} data Data to parse as a valid JSON string
* @return {string} Valid JSON string
*/
function _parseAsJSON(data) {
// Coerce as a string
return '[' + ('' + data).replace(/\r\n?|\n/g, ',') + ']';
}
})(this, this.jQuery);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment