js獲取和下載json文件

業務場景

經過input以json格式上傳配置,直接讀取並加載。再將數據經過json格式下載在本地。json

代碼

<input type="file" accept="application/json", class="upload"/>

$('.upload').click(function(e){
    var target = e.target
    var file = targe.files[0]
    var reader = new FileReader()
    reader.readAsText(file);
    reader.onload = function(){
        var result = JSON.parse(this.result)[0]
    }
})

<input type="button", class="download">

$('.download').click(function(){
    var d = {}
    var datastr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(d));
    var downloadAnchorNode = document.createElement('a')
    downloadAnchorNode.setAttribute("href", datastr);
    downloadAnchorNode.setAttribute("download", 'tem.json')
    downloadAnchorNode.click();
    downloadAnchorNode.remove();
})
相關文章
相關標籤/搜索