将JSON对象转换为缓冲区和缓冲区返回JSON对象

Pra*_*h J 74 buffer json node.js

我有一个JSON对象,我正在将它转换为Buffer并在此处执行一些处理.后来我想转换相同的缓冲区数据以转换为有效的JSON对象.

我正在研究Node V6.9.1

下面是我尝试的代码,但是Buffer当我转换回JSON并且无法打开此对象时我得到了.

var obj = {
   key:'value',
   key:'value',
   key:'value',
   key:'value',
   key:'value'
}

var buf = new Buffer.from(obj.toString());

console.log('Real Buffer ' + buf);  //This prints --> Real Buffer <Buffer 5b 6f 62 6a 65 63 74>

var temp = buf.toString();

console.log('Buffer to String ' + buf);  //This prints --> Buffer to String [object Object]
Run Code Online (Sandbox Code Playgroud)

所以我试图用检查方式打印整个对象

console.log('Full temp ' + require('util').inspect(buf, { depth: null }));  //This prints --> '[object object]' [not printing the obj like declared above]
Run Code Online (Sandbox Code Playgroud)

如果我尝试像数组一样阅读它

 console.log(buf[0]);  // This prints --> [ 
Run Code Online (Sandbox Code Playgroud)

我尝试解析它也扔了 [object object]

我需要将它视为像我创建的真实对象[我的意思就像上面声明的那样].

请帮忙..

Ebr*_*ani 141

你需要对json进行字符串化,而不是调用 toString

var buf = Buffer.from(JSON.stringify(obj));
Run Code Online (Sandbox Code Playgroud)

并将字符串转换为json obj:

var temp = JSON.parse(buf.toString());
Run Code Online (Sandbox Code Playgroud)

  • 如果“obj”中还有另一个缓冲区字段,则这将不起作用 (3认同)
  • 没有更好的解决方案吗?我不喜欢将数字转换为字符串。 (2认同)
  • 实际上,这里不需要toString.https://groups.google.com/forum/#!topic/nodejs/hybuh7DbQkM (2认同)
  • @Dzenly 虽然“toString”在技术上是不需要的,但应该使用它。阅读您链接的页面,它指出缓冲区使用“utf8”编码转换为字符串(使用 Buffer.toString),虽然通常这不是问题,但如果缓冲区是用其他编码创建的,您将得到垃圾。所以说真的,对于这样的事情,应该没问题,但是对于很多其他场景(您几乎无法控制传入的内容),了解并尊重编码是必须的 (2认同)

San*_*ngh 8

在此输入图像描述

请复制以下片段

const jsonObject = {
        "Name":'Ram',
        "Age":'28',
        "Dept":'IT'
      }
      const encodedJsonObject = Buffer.from(JSON.stringify(jsonObject)).toString('base64'); 
      console.log('--encodedJsonObject-->', encodedJsonObject)
      //Output     --encodedJsonObject--> eyJOYW1lIjoiUmFtIiwiQWdlIjoiMjgiLCJEZXB0IjoiSVQifQ==

      const decodedJsonObject = Buffer.from(encodedJsonObject, 'base64').toString('ascii'); 
      console.log('--decodedJsonObject-->', JSON.parse(decodedJsonObject))
      //Output     --decodedJsonObject--> {Name: 'Ram', Age: '28', Dept: 'IT'}
Run Code Online (Sandbox Code Playgroud)