How to convert Javascript Object to ArrayBuffer?

2.2k Views Asked by At

I retrieve an encoded string (using TextEncoder into UTF-8, which was stringified before sending to the server) from the server using AJAX. I parse it upon retrieval and get an Object. I need to convert this Object to a decoded string. TextDecoder seems to have decode method, but it expects ArrayBuffer or ArrayBufferView, not Object. That method gives TypeError if I use my Object as-is:

var myStr = "This is a string, possibly with utf-8 or utf-16 chars.";
console.log("Original: " + myStr);

var encoded = new TextEncoder("UTF-16").encode(myStr);
console.log("Encoded: " + encoded);

var encStr = JSON.stringify(encoded);
console.log("Stringfied: " + encStr);

//---------- Send it to the server; store in db; retrieve it later ---------

var parsedObj = JSON.parse(encStr); // Returns an "Object"
console.log("Parsed: " + parsedObj);

// The following decode method expects ArrayBuffer or ArrayBufferView only
var decStr = new TextDecoder("UTF-16").decode(parsedObj); // TypeError

// Do something with the decoded string

This SO 6965107 has extensive discussion on converting strings/ArrayBuffers but none of those answers work for my situation. I also came across this article, which does not work if I have Object.

Some posts suggest to use "responseType: arraybuffer" which results in ArrayBuffer response from the server, but I cannot use it when retrieving this encoded string because there are many other items in the same result data which need different content-type.

I am kind of stuck and unable to find a solution after searching for a day on google and SO. I am open to any solution that lets me save "strings containing international characters" to the server and "retrieve them exactly as they were", except changing the content-type because these strings are bundled within JSON objects that carry audio, video, and files. Any help or suggestions are highly appreciated.

0

There are 0 best solutions below