JSON.stringify an object with a blob

2.6k Views Asked by At

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.

1

There are 1 best solutions below

2
On BEST ANSWER

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