Created
January 9, 2014 13:41
-
-
Save rdiego26/8334254 to your computer and use it in GitHub Desktop.
Convert ArrayObject to TSV.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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
var arr = [{name:'Diego'}, {name:'Maria'}];
JSON2TSV(arr, {});
"name
Diego
Maria
"