Node.js JSON转换为Buffer

Node.js –要将 JSON 转换为 Buffer,首先将 JSON 对象转换为字符串 JSON.stringify (jsonObj) ; ,然后使用 Buffer.from (jsonStr)方法将 JSON 字符串读取到缓冲区。例
以下是一个示例,演示如何将JSON对象转换为Buffer:
convert-json-to-buffer.js

constmsg='{"name":"John","age":"22"}';varjsonObj=JSON.parse(msg);//将JSON对象转换为StringvarjsonStr=JSON.stringify(jsonObj);//将json字符串读取到缓冲区constbuf=Buffer.from(jsonStr);console.log(buf.length);

输出结果

$nodeconvert-json-to-buffer.js26

在下一个Node.js教程中,我们将学习将Buffer数据转换为JSON对象。

编辑于2024-06-05 16:58