Skip to content

Instantly share code, notes, and snippets.

@rdiego26
Created January 9, 2014 13:41
Show Gist options
  • Save rdiego26/8334254 to your computer and use it in GitHub Desktop.
Save rdiego26/8334254 to your computer and use it in GitHub Desktop.
Convert ArrayObject to TSV.
function JSON2TSV(objArray, options) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
//includeLabels, quoteValues
if(!options || typeof options != 'object') options = {};
if(options.includeLabels === undefined) options.includeLabels = true;
if(options.quoteValues === undefined) options.quoteValues = false;
var str = '';
var line = '';
var sep = '\t';
if(options.includeLabels) {
var head = array[0];
if(options.quoteValues) {
for (var index in array[0]) {
var value = index + "";
line += '"' + value.replace(/"/g, '""') + '"' + sep;
}
} else {
for (var index in array[0]) {
line += index + sep;
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
for (var i = 0; i < array.length; i++) {
var line = '';
if(options.quoteValues) {
for (var index in array[i]) {
var value = array[i][index] + "";
line += '"' + value.replace(/"/g, '""') + '"' + sep;
}
} else {
for (var index in array[i]) {
line += array[i][index] + sep;
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
return str;
}
@rdiego26
Copy link
Author

var arr = new Array({name:'Diego'}, {name:'Maria'});
JSON2TSV(arr, {});
"name
Diego
Maria
"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment