7

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.

4
  • what is the value of buffer.toString() - is it what you expect? Commented Oct 19, 2016 at 0:40
  • 3
    JSON cannot encode binary data. You should parse your buffer (probably as UTF8), or use base64.
    – SLaks
    Commented Oct 19, 2016 at 0:40
  • {cmd:'echo'} is not valid json. cmd and echo need double quotes. You could use eval.
    – adrianj98
    Commented Oct 19, 2016 at 0:42
  • You need to find out the exact format of buffer. You may then use the FileReader API to transform it into a JSON parse-able string Commented Oct 19, 2016 at 0:46

4 Answers 4

15

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);
1
  • 1
    Add JSON.stringify() to write the json to a file, ie: JSON.stringify(JSON.parse(buffer), null, 2). Commented Jun 11, 2020 at 14:20
8

Following should work:

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

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

For nodejs apps, I found String Decoder to work out great.

https://nodejs.org/api/string_decoder.html

// API for decoding Buffer objects into strings
const { StringDecoder } = require('string_decoder');
const decoder = new StringDecoder('utf8');

let body = Buffer.from(response.body);
let json = decoder.write(body);
let foo  = JSON.parse(json);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.