iT邦幫忙

0

[JS疑問]JSON下載成csv檔

想詢問我有一個textarea跟一個按鈕,我想要在textarea內輸入JSON格式,點下按鈕後會自動下載csv檔,目前可成功下載的形式如下

https://ithelp.ithome.com.tw/upload/images/20210901/20135967UR8vuUk9qf.jpg

[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}]		

https://ithelp.ithome.com.tw/upload/images/20210901/20135967Rh718vjUak.jpg

若是輸入以下格式,則會呈現這樣

[{"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"}]

https://ithelp.ithome.com.tw/upload/images/20210901/20135967ViMwlft3nV.jpg

如果要下載後,以下面這樣的格式呈現,應該從何著手修改?
主要Year是取Year.Value的值,Subject1是取Subject1.Value的值
https://ithelp.ithome.com.tw/upload/images/20210901/20135967TMfAcBHkNm.jpg

再麻煩各位指導,感謝QQ

1 個回答

0
Homura
iT邦高手 1 級 ‧ 2021-09-01 10:16:15
最佳解答

你有指定欄位需要再讀詳細
就加個欄位判斷就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] + '",';
        }
    }
}

希希寶 iT邦新手 5 級 ‧ 2021-09-01 10:35:33 檢舉

成功了,感謝!

我要發表回答

立即登入回答