iT邦幫忙

0

python gzip 和 js pako inflate 一問

大家好, 想問一下關於python 和JS的問題

首先就是因為我的geojson file 有800000支以上的record, 我用python 的gzip 把它轉成
ascii

with gzip.open('testing.geojson', 'w') as fout:
    fout.write(json.dumps(d).encode("utf-8"))

之後在js 那邊用pako 來inflate

readTextFile('./datasets/testing.geojson');

var allText = rawFile.responseText;
              
                console.log(Buffer.from(allText).toString('base64'))
                var byteArray = new Uint8Array(Buffer.from(allText).toString('base64'));
                //console.log(byteArray)
                setTimeout(function(){
                    alert("Unzipping data...")
                    result = pako.inflate(byteArray, {to: 'string'});
                    console.log(result)
                },2000)

但是在browser f12 裡看到result 是undefined, 請問哪一步我是寫錯了.
或者我不知道可不可以在python 那邊變成gzip , 再在js 那邊解壓GZIP, 但因為我本身是沒有用node.js , 只是用http server

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

2
淺水員
iT邦大師 6 級 ‧ 2021-11-02 23:38:20
最佳解答

gzip 是二進位資料
處理時直接用二進位的方式讀寫

python 壓縮資料

import json
import gzip

# 測試資料
d=['foo', {'bar': ('baz', None, 1.0, 2)}]

# 壓縮到 data.gz
with gzip.open('data.gz', 'wb') as f:
    f.write(json.dumps(d).encode("utf-8"))

javascript(瀏覽器) 解壓縮取得資料

fetch('data.gz').then(r => {
    if (r.status !== 200) {
        throw '無法取得檔案';
    }
    return r.arrayBuffer();
}).then(buffer => {
    //解壓縮,會拿到一個 Uint8Array
    const result = pako.inflate(buffer);
    console.log(result);

    //用原生的 TextDecoder 解碼為字串(預設是 utf8)
    const textDec = new TextDecoder();
    const str = textDec.decode(result);
    console.log(str);

    //取得 json 物件
    const jsonData = JSON.parse(str);
    console.log(jsonData);
}).catch(e => {
    alert(e);
});
diu7me iT邦新手 4 級 ‧ 2021-11-03 09:20:43 檢舉

你好, 請問一下
d=['foo', {'bar': ('baz', None, 1.0, 2)}]
因為我本身是一個json , 一定要用array 包住嗎?

這樣可以嗎?

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "properties": {
                "olrtoa": 0.0,
                "rainc": 0.0,
                "rainnc": 0.0,
                "refl10cm_max": 0.0,
                "refl10cm_1km": 0.0,
                "refl10cm_1km_max": 0.0,
                "precipw": 41.7464
                ...
                
                ...
                
                ...

謝謝

diu7me iT邦新手 4 級 ‧ 2021-11-03 09:53:35 檢舉

謝謝你, 成功轉換了, 謝謝你救了我的一天和你寶貴的時間,感激/images/emoticon/emoticon02.gif

1
hokou
iT邦好手 1 級 ‧ 2021-11-02 15:33:54

我認為是因為 setTimeout 導致

建議先把 setTimeout 拿掉進行測試或是把 var 那些放到 setTimeout 的函式裡面

diu7me iT邦新手 4 級 ‧ 2021-11-02 15:55:36 檢舉

試過都一樣

我要發表回答

立即登入回答