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); }
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');