Search code examples
javascriptjsonlibsox

JSON.stringify an object with a blob


I have an object with an audio blob inside of it. When I call JSON.stringify on the object, the blob disappears. How to stringify a binary blob in an object ?

The audio blob is from the sox-element and in this case is of mime type 'audio/wav'.

let blob = this/soxElem.getBlob();
let object = {
  audio: blob,
  name: "hi"
}

console.log(JSON.stringify(object))

The console shows {audio:{}, name: "hi"}. The blob is gone.


Solution

  • One way to do it is to convert to an array which JSON can handle :

    let ab = await this.soxElem.getBlob().arrayBuffer();
    let object = {
      audio: Array.from(new Uint8Array(ab)),
      name: "hi"
    }
    

    On the receiving side (e.g. with Node.js) decode it like so :

    let binaryData = Buffer.from(data.audio);