我将CSV转换为JSON数据的算法有效,但是当我单击“下载JSON”时,它会给我一个CSV文件。有人知道问题出在哪里吗?
此外,“转换为CSV”按钮未输出任何内容!
即使我包含了Highcharts代码,您也不必关注它。
有人知道如何解决此问题吗?代码在这里(一些代码来自JSFiddle的Sturtevant。感谢他):
function CSVToArray(strData, strDelimiter) {
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp((
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"), "gi");
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec(strData)) {
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[1];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter)) {
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push([]);
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[2]) {
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[2].replace(
new RegExp("\"\"", "g"), "\"");
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[3];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[arrData.length - 1].push(strMatchedValue);
}
// Return the parsed data.
return (arrData);
}
function CSV2JSON(csv) {
var array = CSVToArray(csv);
var objArray = [];
for (var i = 1; i < array.length; i++) {
objArray[i - 1] = {};
for (var k = 0; k < array[0].length && k < array[i].length; k++) {
var key = array[0][k];
objArray[i - 1][key] = array[i][k]
}
}
var json = JSON.stringify(objArray);
var str = json.replace(/},/g, "},\r\n");
return str;
}
$("#convert").click(function() {
var csv = $("#csv").val();
var json = CSV2JSON(csv);
$("#json").val(json);
});
$("#download").click(function() {
var csv = $("#csv").val();
var json = CSV2JSON(csv);
window.open("data:text/json;charset=utf-8," + escape(json))
});
function JSON2CSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var line = '';
if ($("#labels").is(':checked')) {
var head = array[0];
if ($("#quote").is(':checked')) {
for (var index in array[0]) {
var value = index + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
} else {
for (var index in array[0]) {
line += index + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
for (var i = 0; i < array.length; i++) {
var line = '';
if ($("#quote").is(':checked')) {
for (var index in array[i]) {
var value = array[i][index] + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
} else {
for (var index in array[i]) {
line += array[i][index] + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
return str;
}
$("#convert").click(function() {
var json = $.parseJSON($("#json").val());
var csv = JSON2CSV(json);
$("#csv").val(csv);
});
$("#download").click(function() {
var json = $.parseJSON($("#json").val());
var csv = JSON2CSV(json);
window.open("data:text/csv;charset=utf-8," + escape(csv))
});
var myJson = [{"category":1,"guestValue":0,"visits":23},{"category":2,"guestValue":96.6,"visits":45},{"category":3,"guestValue":73.2,"visits":65},{"category":4,"guestValue":60.3,"visits":85},{"category":5,"guestValue":52.5,"visits":105},{"category":6,"guestValue":46.6,"visits":125},{"category":7,"guestValue":41.4,"visits":144},{"category":8,"guestValue":37.5,"visits":163},{"category":9,"guestValue":34.4,"visits":179},{"category":10,"guestValue":31.9,"visits":199},{"category":"11-17","guestValue":25.4,"visits":258},{"category":"18-28","guestValue":17,"visits":394},{"category":"29+","guestValue":9.7,"visits":847}];
var category = [];
var guestValue = [];
var visits = [];
for (i=0; i < myJson.length; i++) {
guestValue.push(myJson[i].guestValue);
visits.push(myJson[i].visits);
category.push(myJson[i].category);
}
Highcharts.chart('container', {
chart: {
type: 'bar'
},
title: {
text: null,
align: 'center',
verticalAlign: 'bottom',
},
xAxis: {
categories: category,
title: {
text: 'Visits Per Customer (TTM)'
},
},
yAxis: {
min: 0,
gridLineWidth: 0,
minorGridLineWidth: 0,
title: {
text: 'Average Return Rate Overall: 64 Days',
y: 10
},
labels: {
overflow: 'justify'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.0f} </b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
bar: {
dataLabels: {
enabled: true,
}
}
},
legend: {
layout: 'horizontal',
align: 'right',
verticalAlign: 'top',
x: -25,
y: 5,
width: 280,
floating: true,
borderWidth: 1,
backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
shadow: true
},
credits: {
enabled: false
},
series: [{
name: 'Q1 / 18 (TTM) Annual Guest Value',
data: guestValue,
color: 'grey',
// label color
dataLabels: {
style: {
color: 'grey'
}
}
}, {
name: 'Days Between 1st and 2nd Visits',
data: visits,
color: 'green',
// label color
dataLabels: {
style: {
color: 'green'
}
}
}]
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<!--alasql library-->
<script src="https://cdn.jsdelivr.net/alasql/0.3/alasql.min.js"></script>
<div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>
<script>
angular.module('app', []).controller('downloader', function($scope) {
// json data to be exported
$scope.data = [{"category":1,"guestValue":0,"visits":23},{"category":2,"guestValue":96.6,"visits":45},{"category":3,"guestValue":73.2,"visits":65},{"category":4,"guestValue":60.3,"visits":85},{"category":5,"guestValue":52.5,"visits":105},{"category":6,"guestValue":46.6,"visits":125},{"category":7,"guestValue":41.4,"visits":144},{"category":8,"guestValue":37.5,"visits":163},{"category":9,"guestValue":34.4,"visits":179},{"category":10,"guestValue":31.9,"visits":199},{"category":"11-17","guestValue":25.4,"visits":258},{"category":"18-28","guestValue":17,"visits":394},{"category":"29+","guestValue":9.7,"visits":847}];
$scope.downloadReports = function() { // we can download our json data in many formats. ex: csv, excel
// var filename = "someFileName.xlsx"
var filename = "RawData.csv"
//alasql('SELECT id as ID,name as Name INTO XLSX("' + filename + '",{headers:true}) FROM ?', [$scope.OrganizationUsersList]);
alasql('SELECT * INTO CSV("' + filename + '",{headers:true}) FROM ?', [$scope.data]);
};
$scope.downloadReports_xlsx = function() {
var filename = "RawData.xlsx"
// alasql('SELECT * INTO XLSML("RawData.xls",?) FROM ?',[$scope.data]);
alasql('SELECT * INTO XLSX("' + filename + '",{headers:true}) FROM ?', [$scope.data]);
};
});
</script>
</head>
<body ng-app="app" ng-controller="downloader">
<div style="float: left">
<button class="btn btn-xs btn-white" ng-click="downloadReports()">Download CSV Report</button>
<button class="btn btn-xs btn-white" ng-click="downloadReports_xlsx()">Download Excel Report</button>
<p id="heading">CSV to JSON Converter</p>
<p class="small"><a href="http://jsfiddle.net/sturtevant/vUnF9/" target="_blank">JSON to CSV Converter</a>
<hr />
<p>Paste Your CSV Here:</p>
<textarea id="csv" class="text">"Id","UserName"
"1","Sam Smith"
"2","Fred Frankly"
"1","Zachary Zupers"</textarea>
<br />
<button id="convert">Convert to JSON</button>
<button id="download">Download JSON</button>
<textarea id="json" class="text"></textarea>
<p>Based on code posted <a href="http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm" target="_blank">here on Ben Nadel's blog</a></p>
</div>
</body>
<body ng-app="app" ng-controller="downloader">
<div style="float: left">
<p id="heading">JSON to CSV Converter</p>
<p class="small"><a href="http://jsfiddle.net/sturtevant/AZFvQ/" target="_blank">CSV to JSON Converter</a>
<hr />
<p>Paste Your JSON Here:</p>
<textarea id="json" class="text">[{"Id":1,"UserName":"Sam Smith"},
{"Id":2,"UserName":"Fred Frankly"},
{"Id":1,"UserName":"Zachary Zupers"}]</textarea>
<br />
<input id="quote" type="checkbox" checked="true" /> Wrap values in double quotes
<br />
<input id="labels" type="checkbox" checked="true" /> Include labels in first row
<br />
<button id="convert">Convert to CSV</button>
<button id="download">Download CSV</button>
<textarea id="csv" class="text"></textarea>
<p>Based on code posted <a href="http://stackoverflow.com/a/4130939/317" target="_blank">here on StackOverflow</a></p>
</div>
</body>
</html>
答案 0 :(得分:1)
当我单击“下载JSON”时,它会给我一个CSV文件
<button id="download">Download JSON</button>
...
$("#download").click(function() {
var json = $.parseJSON($("#json").val());
var csv = JSON2CSV(json);
window.open("data:text/csv;charset=utf-8," + escape(csv))
});
看起来就是您要它做的...