想詢問我有一個textarea跟一個按鈕,我想要在textarea內輸入JSON格式,點下按鈕後會自動下載csv檔,目前可成功下載的形式如下
[HTML]
<div class='mydiv'>
<textarea id="txt" class='txtarea'> </textarea>
<button class='btn_download'>Download</button>
</div>
[JS]
$(document).ready(function(){
$('button').click(function(){
var data = $('#txt').val();
if(data == '')
return;
JSONToCSVConvertor(data, "Vehicle Report", true);
});
});
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = 'sep=,' + '\r\n\n';
if (ShowLabel) {
var row = "";
for (var index in arrData[0]) {
row += index + ',';
}
row = row.slice(0, -1);
CSV += row + '\r\n';
}
for (var i = 0; i < arrData.length; i++) {
var row = "";
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
var fileName = "JSON_TO_CSV";
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = fileName + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
若我輸入以下格式的JSON,下載後會呈現這樣
[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road, West Bengal 734013, India","Speed":0},{"Vehicle":"Supra","Date":"30, Jul 2013 07:53 AM","Location":"Sec-45, St. Angel's School, Gurgaon, Haryana, India","Speed":58},{"Vehicle":"Land Cruiser","Date":"30, Jul 2013 09:35 AM","Location":"DLF Phase I, Marble Market, Gurgaon, Haryana, India","Speed":83},{"Vehicle":"Suzuki Swift","Date":"30, Jul 2013 12:02 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0},{"Vehicle":"Honda Civic","Date":"30, Jul 2013 12:00 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0},{"Vehicle":"Honda Accord","Date":"30, Jul 2013 11:05 AM","Location":"DLF Phase IV, Super Mart 1, Gurgaon, Haryana, India","Speed":71}]
若是輸入以下格式,則會呈現這樣
[{"Year":{"Value":"2021","SubjectType":"year"},"Subject1":{"Value":"JP","SubjectType":"country"},"Subject2":null,"Value":"33087"},{"Year":{"Value":"2021","SubjectType":"year"},"Subject1":{"Value":"TW","SubjectType":"country"},"Subject2":null,"Value":"7525"}]
如果要下載後,以下面這樣的格式呈現,應該從何著手修改?
主要Year是取Year.Value的值,Subject1是取Subject1.Value的值
再麻煩各位指導,感謝QQ
你有指定欄位需要再讀詳細
就加個欄位判斷就OK
for (var i = 0; i < arrData.length; i++) {
var row = "";
for (var index in arrData[i]) {
// 判斷是不是Year和Subject1
if(index==='Year' || index==='Subject1')
{
row += '"' + arrData[i][index]['Value'] + '",';
}
else
{
row += '"' + arrData[i][index] + '",';
}
}
}