Node.js –要將 JSON 轉(zhuǎn)換為 Buffer,首先將 JSON 對象轉(zhuǎn)換為字符串 JSON.stringify (jsonObj) ; ,然后使用 Buffer.from (jsonStr)方法將 JSON 字符串讀取到緩沖區(qū)。例
以下是一個示例,演示如何將JSON對象轉(zhuǎn)換為Buffer:
convert-json-to-buffer.js
const msg = '{"name":"John", "age":"22"}';
var jsonObj = JSON.parse(msg);
//將 JSON 對象轉(zhuǎn)換為 String
var jsonStr = JSON.stringify(jsonObj);
//將json字符串讀取到緩沖區(qū)
const buf = Buffer.from(jsonStr);
console.log(buf.length);輸出結(jié)果
$ node convert-json-to-buffer.js 26
在下一個Node.js教程中,我們將學(xué)習(xí)將Buffer數(shù)據(jù)轉(zhuǎn)換為JSON對象。