Javascript from Buffer to JSON
Javascript from Buffer to JSON
我使用bleno(一个node js BLE包),它使用Buffer来发送和接收数据。如何获取Buffer对象并将其转换为JSON?这是我现在的文件:
bufferToJson = buffer.toString();
bufferToJson = JSON.stringify(bufferToJson)
bufferToJson = JSON.parse(bufferToJson)
缓冲区是数据所在。缓冲可以是{cmd:'echo'}
的一个例子,我尝试过bufferToJson.cmd
,只得到未定义。谢谢。
如果您的缓冲区对象包含JSON的有效表示,那么转换它的最简单方法如下:
const json = JSON.parse(buffer);
以下内容可以:
var bufferToJson = JSON.parse(myBuffer.toString());
您可以使用TextDecoder如下片段:
const buffer = await characteristic.readValue();
const decoder = new TextDecoder('utf8');
const text = decoder.decode(buffer);
console.log(JSON.parse(text));
对于nodejs应用程序,我发现字符串解码器工作得很好。
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);
相关文章:
- Javascript: parse json to list
- response json to javascript
- AngularJS - Json to Tree structure
- Dojo 如何解析整个 JsonRestStore (JSON to String)
- JSON to Object - JavaScript
- PHP JSON to JavaScript Array
- JSON to DOM or innerHTML?
- JSON to javascript Date.UTC
- jQuery JSON to Javascript
- From json to ul li
- Google maps API: JSON to jQuery
- Backbone.js fetch() JSON to model get() returns undefined
- JSON to setAttribute()
- "Nested" JSON to "unnested" JSON in Java
- json to 2d javascript array
- PHP Array JSON to Javascript
- Javascript JSON to PHP Array
- Passing a JSON to PHP
- Meteor Restivus - POST body (JSON) to mongoDB
- JSON to html STYLED table