Javascript from Buffer to JSON

17,934

Solution 1

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);

Solution 2

Following should work:

var bufferToJson = JSON.parse(myBuffer.toString());

Solution 3

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));
Share:
17,934
JorgeC
Author by

JorgeC

College Dropout. Aspiring Polymath. Product & Machine Learning.

Updated on June 16, 2022

Comments

  • JorgeC
    JorgeC almost 2 years

    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.