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.
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.
The toJSON() method returns a JSON object based on the Buffer object.
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.
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.
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);
Following should work:
var bufferToJson = JSON.parse(myBuffer.toString());
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));
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