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?
var u8 = new Uint8Array([65, 66, 67, 68]); var decoder = new TextDecoder('utf8'); var b64encoded = btoa(decoder. decode(u8)); If you need to support browsers that do not have TextDecoder (currently just IE and Edge), then the best option is to use a TextDecoder polyfill.
parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With