在JS有一個參數我用 log print 出來長這樣 values = Uint8Array(87818240) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 請問如果我在 django 有一個 3D 陣列 要如何轉換成這個JS格式?

 

 


如果你在 Django(Python)中有一個 3D 陣列(例如形狀為 [depth][height][width]numpy 陣列或 list),你想要在前端 JavaScript 中將它變成:

Uint8Array([...])

這裡的關鍵是:

  1. 將 3D 陣列「攤平成一維(flattened)」

  2. 轉為 bytes 或 base64(用於傳輸)

  3. 在 JavaScript 中還原為 Uint8Array


✅ 方法一:使用 base64 傳輸

這是最常見且安全的做法:

? Django 端(Python)

import numpy as np
import base64
from django.http import JsonResponse

def get_array_data(request):
    # 假設你有一個 3D 的 uint8 numpy 陣列
    arr = np.random.randint(0, 256, size=(100, 100, 100), dtype=np.uint8)
    arr_bytes = arr.tobytes()  # 轉成 bytes
    arr_base64 = base64.b64encode(arr_bytes).decode('utf-8')  # 轉成 base64 字串

    shape = arr.shape  # 用來還原 3D 陣列
    return JsonResponse({'data': arr_base64, 'shape': shape})
前端 JS

fetch("/your-api-url")
  .then(res => res.json())
  .then(({ data, shape }) => {
    // base64 decode
    const binary = atob(data);
    const len = binary.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binary.charCodeAt(i);
    }

    console.log("Flattened Uint8Array:", bytes);

    // 如果你要還原為 3D 陣列,可用 shape
    const [D, H, W] = shape;
    const array3D = [];
    let idx = 0;
    for (let d = 0; d < D; d++) {
      const slice = [];
      for (let h = 0; h < H; h++) {
        const row = [];
        for (let w = 0; w < W; w++) {
          row.push(bytes[idx++]);
        }
        slice.push(row);
      }
      array3D.push(slice);
    }
    console.log("Restored 3D Array:", array3D);
  });

方法二:直接傳送一維列表(不建議太大時使用)

若資料不大,也可以 Django 直接回傳 list(缺點:傳輸量大,速度慢)

Django:

import numpy as np
from django.http import JsonResponse

def get_array_data(request):
    arr = np.random.randint(0, 256, size=(100, 100, 100), dtype=np.uint8)
    flat_list = arr.flatten().tolist()
    return JsonResponse({'data': flat_list})

JS:

fetch("/your-api-url")
  .then(res => res.json())
  .then(({ data }) => {
    const arr = new Uint8Array(data);
    console.log(arr);
  });

總結

方法優點缺點
Base64 傳輸 適合大資料、快速、安全 前後端需額外解碼
直接傳 list 寫法簡單 效率差、資料大會卡死

如你這筆資料長度是 87,818,240(約 83MB),建議用 Base64 壓縮後傳輸,才不會卡爆網頁。