I searched on stackoverflow already, and couldn't find an answer for converting an array buffer to an object; only found answers for a string.
I tried to follow answers using string methods and translate that to object methids but I couldn't figure it out.
This is what I am getting on the client side. I want to convert this back to an object:
Array [
123,
34,
114,
101,
97,
100,
34,
58,
102,
97,
108,
115,
101,
44,
34,
116,
105,
109,
101,
83,
101,
110,
116,
34,
58,
49,
54,
52,
54,
49,
55,
49,
57,
50,
50,
55,
48,
49,
44,
34,
109,
101,
115,
115,
97,
103,
101,
34,
58,
34,
101,
116,
114,
104,
34,
44,
34,
117,
115,
101,
114,
73,
68,
34,
58,
52,
55,
44,
34,
99,
111,
110,
116,
97,
99,
116,
73,
68,
34,
58,
52,
55,
125,
]
This function converts from the array to a string:
function arrayBufferToString(buffer) {
var arr = new Uint8Array(buffer);
var str = String.fromCharCode.apply(String, arr);
if (/[\u0080-\uffff]/.test(str)) {
throw new Error(
"this string seems to contain (still encoded) multibytes"
);
}
return str;
}
This is what I am getting after running the above function:
{"read":false,"timeSent":1646174304184,"message":"hjefjhewk","userID":47,"contactID":47}
This is the expected output/return value:
{
read: false,
timeSent: 1646196262824,
message: 'Hi',
userID: 41,
contactID: 47
}
If I get the issue correctly, you need just parse json string to the object:
const arr = [123,34,114,101,97,100,34,58,102,97,108,115,101,44,34,116,105,109,101,83,101,110,116,34,58,49,54,52,54,49,55,49,57,50,50,55,48,49,44,34,109,101,115,115,97,103,101,34,58,34,101,116,114,104,34,44,34,117,115,101,114,73,68,34,58,52,55,44,34,99,111,110,116,97,99,116,73,68,34,58,52,55,125];
const str = String.fromCharCode.apply(String, arr);
const obj = JSON.parse(str);
console.log(obj);
.as-console-wrapper{min-height: 100%!important; top: 0}