javascript-解压json,将缓冲区转换为字符串

时间:2018-10-20 19:17:36

标签: javascript json client-side jszip

我正在使用JSZipUtils解压缩json文件:

<head>
    <meta charset="UTF-8">
    <script src="node_modules/jszip/dist/jszip.min.js"></script>
    <script src="node_modules/file-saver/dist/FileSaver.min.js"></script>
    <script src="node_modules/jszip-utils/dist/jszip-utils.min.js"></script>    
</head>

<script>
JSZipUtils.getBinaryContent('data/top8.json.zip', function(err, data) {
    if(err) {
        throw err; // or handle err
    }

    JSZip.loadAsync(data).then(function () {
        console.log(data);
    });
});
</script>

我收到以下答复:

enter image description here

所需的响应:

enter image description here

1 个答案:

答案 0 :(得分:0)

这就是最终的结果:

<head>
    <script src="lzwCompress.js"></script>
</head>

<script>
var lzwCompress = window.lzwCompress;
json_path = "data/top8.json";

function compress() {
    xttp = new XMLHttpRequest();
    xttp.open("GET", json_path);
    xttp.send();
    xttp.onreadystatechange= function() {
        if(this.readyState == 4 && this.status == 200){
            var data = JSON.parse(this.responseText);
            var compressed = lzwCompress.pack(data);
            var compressed = JSON.stringify(compressed)
            download(compressed, 'top8_compressed.json', 'utf8');
        }
    }
}

function decompress() {
    xttp = new XMLHttpRequest();
    xttp.open("GET", "data/top8_compressed.json");
    xttp.send();
    xttp.onreadystatechange= function() {
        if(this.readyState == 4 && this.status == 200){
            var data = JSON.parse(this.responseText);
            var original = lzwCompress.unpack(data);
            console.log(original);
        }
    }
}

function download(content, fileName, contentType) {
    var a = document.createElement("a");
    var file = new Blob([content], {type: contentType});
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
}

compress();
decompress();
</script>