js 下载json数组文件


 日常中,我们的json数据格式位置错乱等等操做,我们可以利用js来排序好然后下载下来使用

案例:

$(document).ready(function() {
   var jsonData = [
    { id: '1001', name: 'dog', age: '10'},
    { id: '1003', name: 'big', age: '12'},
    { id: '1002', name: 'cat', age: '11'}
    ];
    jsonData.sort(function(a,b){
    return a.age - b.age;
    });
    saveJSON(jsonData, 'jsonData.json');
})
function saveJSON(data, filename) {
    if (!data) {
        alert('data is null');
        return;
    }
    if (!filename) filename = 'json.json'
    if (typeof data === 'object') {
        data = JSON.stringify(data, undefined, 4)
    }
    var blob = new Blob([data], { type: 'text/json' });
    var e = document.createEvent('MouseEvents');
    var a = document.createElement('a');
    a.download = filename;
    a.href = window.URL.createObjectURL(blob);
    a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    a.dispatchEvent(e);
}
View Code

 

 

json格式:

var jsonData = [
    { id: '1001', name: 'dog', age: '10'},
    { id: '1003', name: 'big', age: '12'},
    { id: '1002', name: 'cat', age: '11'}
]

 

 

 saveJson:

function saveJSON(data, filename) {
    if (!data) {
        alert('data is null');
        return;
    }
    if (!filename) filename = 'json.json'
    if (typeof data === 'object') {
        data = JSON.stringify(data, undefined, 4)
    }
    var blob = new Blob([data], { type: 'text/json' });
    var e = document.createEvent('MouseEvents');
    var a = document.createElement('a');
    a.download = filename;
    a.href = window.URL.createObjectURL(blob);
    a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    a.dispatchEvent(e);
}

 

 使用:

saveJSON(jsonData, 'jsonData1.json');

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM