问题
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.
回答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);
回答2:
Following should work:
var bufferToJson = JSON.parse(myBuffer.toString());
回答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));
回答4:
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);
来源:https://stackoverflow.com/questions/40120232/javascript-from-buffer-to-json