Search code examples
javascriptjsonclient-sidejszip

javascript - unzip json, convert buffer to string


I am using JSZipUtils to unzip a json file:

<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>

I am getting the below response:

enter image description here

Desired response:

enter image description here


Solution

  • This is what ended up working:

    <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>