将JSON对象转换为Buffer并将Buffer转换为JSON对象 [英] Convert a JSON Object to Buffer and Buffer to JSON Object back

查看:1113
本文介绍了将JSON对象转换为Buffer并将Buffer转换为JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a JSON object and I'm converting it to a Buffer and doing some process here. Later I want to convert the same buffer data to convert to valid JSON object.

我正在研究Node V6.9.1

I'm working on Node V6.9.1

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

Below is the code I tried but I'm getting [object object] when I convert back to JSON and cannot open this object.

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]

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

So I tried to print whole object using inspect way

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

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

If i try to read it like an array

 console.log(buf[0]);  // This prints --> [ 

我也尝试解析它引发SyntaxError: Unexpected token o in JSON at position 2

我需要像创建一样将其视为真实对象(我的意思是像上面声明的那样).

I need to view it as real object like I created (I mean like declared above).

请帮助.

推荐答案

您需要对json进行字符串化处理,而不要调用toString

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

用于将字符串转换为json obj

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

这篇关于将JSON对象转换为Buffer并将Buffer转换为JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆