Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: How do I convert Uint8Array data to a JS object

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?

like image 522
Siddartha Avatar asked May 24 '13 00:05

Siddartha


People also ask

How do I encode Uint8Array?

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.

Which methods convert a JSON string to a JavaScript object?

parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

How do you convert JavaScript data into JSON?

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.

How do you convert an object in JavaScript?

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.


1 Answers

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.

like image 63
Bergi Avatar answered Sep 28 '22 10:09

Bergi