I am new to both Javascript and JSON worlds. I am wondering how I could convert an incoming Uint8Array data () to a JS object? Any help / pointers please. Here's what I have done as an experiment.
// arr is uint8Array incoming data
function myConvertFunc(arr) {
let str = "";
for (var i=0; i<arr.byteLength; i++) {
str += String.fromCharCode(arr[i]);
}
// Say, 'str' at this step looks like below :
/* {"type": "newEvent", "content": {"rec": [{"id1": "1", "event": "3A=","payload": "EZm9ydW0ub="}]}} */
var serializedData = JSON.stringify(str);
let message = JSON.parse(serializedData);
switch (message.type) {
case "newEvent":
log("In newEvent");
break;
.
.
.
default:
log("undefined message type");
}
}
Contrary to my understanding, the default case log : "undefined message type" is show in my logs. Could someone please help me figure out my mistake here?
-
3What is a "Uint8Array"?Matt Ball– Matt Ball2013年05月24日 00:02:25 +00:00Commented May 24, 2013 at 0:02
-
The Uint8Array type represents an array of 8-bit unsigned integers. Not sure if this is the answer you are looking forSiddartha– Siddartha2013年05月24日 00:04:40 +00:00Commented May 24, 2013 at 0:04
-
@MattBall: It's a typed array. See developer.mozilla.org/en-US/docs/JavaScript/Typed_arrays/…Bergi– Bergi2013年05月24日 00:13:09 +00:00Commented May 24, 2013 at 0:13
-
1@Siddartha: Why do you need to put a JSON string into a typed array (or the other way round)?Bergi– Bergi2013年05月24日 00:14:46 +00:00Commented May 24, 2013 at 0:14
1 Answer 1
var serializedData = JSON.stringify(str); let message = JSON.parse(serializedData);
That means if there are no errors that str === serializedData
(or at least two equal-looking objects).
Say, 'str' at this step looks like below:
{"type": "newEvent", "content": {"rec": [{"id1": "1", "event": "3A=","payload": "EZm9ydW0ub="}]}}
Now, if str
is the JSON string then you just want
var message = JSON.parse(str);
Currently, you did JSON-encode and then -decode the JSON string, with the result that message
was the string again and its type
property was undefined
.
3 Comments
console.log(str)
to make sure it is valid - not sure where you got your uint8array from and what else it might contain.