Javascript from Buffer to JSON

本小妞迷上赌 提交于 2021-01-21 08:30:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!