Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript from Buffer to JSON

I'm using bleno (A node js BLE package) and it uses Buffer to send and receive data. How will I go about getting a Buffer object and converting it into JSON? This is what i have now:

bufferToJson = buffer.toString();
bufferToJson = JSON.stringify(bufferToJson)
bufferToJson = JSON.parse(bufferToJson)

buffer is where the data is. An example of what buffer can be is {cmd:'echo'} I have tried bufferToJson.cmd and only get undefine. Thanks.

like image 227
JorgeC Avatar asked Oct 19 '16 00:10

JorgeC


People also ask

How will you convert a buffer to JSON in node JS?

The Buffer. toJSON() method returns the buffer in JSON format. Note: The JSON. Stringify() is the method which can also be used to return the data in JSON format.

Which of the following code converts a buffer buf to JSON object?

The toJSON() method returns a JSON object based on the Buffer object.

Can JavaScript write to a JSON file?

If we want to write something in a JSON file using JavaScript, we will first need to convert that data into a JSON string by using the JSON. stringify method. Above, a client object with our data has been created which is then turned into a string. This is how we can write a JSON file using the fileSystem.

How convert buffer to string in react?

Buffers have a toString() method that you can use to convert the buffer to a string. By default, toString() converts the buffer to a string using UTF8 encoding. For example, if you create a buffer from a string using Buffer. from() , the toString() function gives you the original string back.


3 Answers

If your buffer object contains a valid representation of a JSON, then the easiest way to convert it would be like so:

const json = JSON.parse(buffer);
like image 110
MauricioLeal Avatar answered Oct 17 '22 19:10

MauricioLeal


Following should work:

var bufferToJson = JSON.parse(myBuffer.toString());
like image 7
TobiasR. Avatar answered Oct 17 '22 20:10

TobiasR.


You can use TextDecoder as in following fragment:

const buffer = await characteristic.readValue();
const decoder = new TextDecoder('utf8');
const text = decoder.decode(buffer);
console.log(JSON.parse(text));
like image 1
Nikolay Avatar answered Oct 17 '22 21:10

Nikolay