javascript - распаковать json, преобразовать буфер в строку - PullRequest
0 голосов
/ 20 октября 2018

Я использую 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 голосов
/ 21 октября 2018

Вот что получилось:

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