首页 > 解决方案 > 为什么必须 json.parse(buffer.concat(chunks)) 两次?

问题描述

通过 http.request 获取 json 数据,我能够以块的形式接收数据,并将其推送到一个数组中。当请求结束时,我使用 buffer.concat 连接数组,然后 json.parse 这个对象,这给了我一个字符串。然后我必须再次 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();

标签: javascriptjsonnode.jsparsing

解决方案


推荐阅读