Javascript 为什么需要两次json.parse(buffer.concat(chunks))呢?

Javascript 为什么需要两次json.parse(buffer.concat(chunks))呢?,javascript,json,node.js,parsing,Javascript,Json,Node.js,Parsing,通过http.request获取json数据,我能够以块的形式接收数据,并将其推送到数组中。当发出请求结束的信号时,我使用buffer.concat连接数组,然后使用json.parse这个对象,这会给我一个字符串。然后我必须再次解析这个字符串以获得一个json对象。为什么我必须两次解析json.parse?有没有更好的方法来实现有效的json对象?这是我的密码: // requires Node.js http module var http = require('http'); var o

通过http.request获取json数据,我能够以块的形式接收数据,并将其推送到数组中。当发出请求结束的信号时,我使用buffer.concat连接数组,然后使用json.parse这个对象,这会给我一个字符串。然后我必须再次解析这个字符串以获得一个json对象。为什么我必须两次解析json.parse?有没有更好的方法来实现有效的json对象?这是我的密码:

// requires Node.js http module
var http = require('http');

var options = {
    "method" : "GET",
    "hostname" : "localhost",
    "port" : 3000,
    "path" : `/get`

};

var req = http.request(options, function (res) {
    var chunks = [];
    console.log(res.statusCode);
    res.on("data", function (chunk) {
        // add each element to the array 'chunks'
        chunks.push(chunk);
    });
    // adding a useless comment...
    res.on("end", function () {

        // concatenate the array
        // iterating through this object spits out numbers (ascii byte values?)
        var jsonObj1 = Buffer.concat(chunks);
        console.log(typeof(jsonObj1));    

        // json.parse # 1
        // iterating through this string spits out one character per line
        var jsonObj = JSON.parse(jsonObj1);
        console.log(typeof(jsonObj));

        // json.parse # 2    
        // finally... an actual json object
        var jsonObj2 = JSON.parse(jsonObj);
        console.log(typeof(jsonObj2));

        for (var key in jsonObj2) {
            if (jsonObj2.hasOwnProperty(key)) {
                var val = jsonObj2[key];
                console.log(val);
            }
        }
    });
});

req.on('error', (e) => {
    console.error(`problem with request: ${e.message}`);
  });

req.end();

服务器以json编码字符串的形式提供编码的json?如果必须对其进行两次解析,则表示服务器对其进行了两次编码。@Barmar,是什么让节点服务器对数据进行两次编码?我目前正在从事一个大量使用流的项目,但我从未遇到过这个问题。@planet\u hunter调用了两次
JSON.stringify()
。或者您正在调用一个自动stringify的响应方法,但您首先调用了参数stringify。@Barmar,谢谢!因此,我尝试使用
request
访问带有字符串化JSON的文件。现在我尝试了
JSON.parse()
,得到了错误
SyntaxError:JSON中的意外标记n位于位置3
,这意味着存储在缓冲区中的字符串化JSON无法转换。但是,当我执行
Buffer.toString()
时,我在控制台中得到了字符串化的JSON。不确定我是否做错了什么,但事情并不像我想的那么简单。