(function ($) {
$.json2csv = function (data, options) {
var settings = $.extend({
header: true,
delimiter: ',',
columnnames: "",
columnkeys: "",
}, options);
options = $.extend(settings, options);
var obj = data;
if (typeof obj === "string") {
obj = $.parseJSON(obj);
}
//need double quotes
function needquotes(value) {
if (value.indexOf('"') != -1) {
return true;
}
else if (new RegExp(/^[0-9]{12,}/).test(value)) {
return true;
}
return false;
}
function str2cell(value) {
if (needquotes(value)) {
return '"' + value.replace(/"/g, '""') + '"';
}
else {
return value;
}
};
function item2row(array) {
var flag = false;
var line = "";
for (var i = 0; i < array.length; i++) {
flag = false;
for (var index in array[i]) {
if (flag) {
line += options.delimiter;
}
else {
flag = true;
}
var value = array[i][index] + "";
str2cell(value);
line += str2cell(value);
}
line += '\r\n';
}
return line;
};
function array2row(array) {
var flag = false;
var line = "";
for (var index in array) {
if (flag) {
line += options.delimiter;
}
else {
flag = true;
}
var value = index + "";
str2cell(value);
line += str2cell(value);
}
return line;
}
var str = "";
if (obj.length) {
var array = obj;
var flag = false;
//header
if (options.header) {
if (options.columnnames.length) {
str += options.columnnames + '\r\n';
}
else {
var head = array[0];
str += array2row(head) + '\r\n';
}
}
//rows
if (options.columnkeys.length) {
str += item2row(array);
}
else {
str += item2row(array);
}
}
return str;
};
}(jQuery));
jquery.json2csv.js
最新推荐文章于 2024-08-08 07:22:10 发布