Javascript Node.js通过WebSocket的JSON格式问题

Javascript Node.js通过WebSocket的JSON格式问题,javascript,json,node.js,web-services,socket.io,Javascript,Json,Node.js,Web Services,Socket.io,我有以下Node.js代码,它调用weather Web服务以获取json repsonse: var reqGet = https.request(optionsgetmsg, function(res) { console.log("statusCode: ", res.statusCode); // uncomment it for header details // console.log("headers: ", res.headers); res.on('data', func

我有以下Node.js代码,它调用weather Web服务以获取json repsonse:

var reqGet = https.request(optionsgetmsg, function(res) {
console.log("statusCode: ", res.statusCode);
// uncomment it for header details
//  console.log("headers: ", res.headers);


res.on('data', function(d) {
    console.info('GET result after POST:\n');

    process.stdout.write(d);        

    console.info('\n\nCall completed');

});
return d;
});
当我使用
process.stdout.write(d)
时,终端的输出是非常JSON格式的文本,如下所示:

{
  "response": {
  "version":"0.1",
  "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
  "features": {
  "geolookup": 1
  ,
  "conditions": 1
  }
    }
        ,       "location": {
        "type":"CITY",
        "country":"US",
        "country_iso3166":"US",
        "country_name":"USA",
        "state":"IN",
        "city":"Indianapolis",
        "tz_short":"EDT",
        "tz_long":"America/Indianapolis"
        }
}
然而,当我尝试使用socket.io发出d时,在chromedev工具中查看对象时,它会变成一堆数字

io.sockets.on('connection',function(socketWeather){
    socketWeather.emit('weather', { weather: d });

});
Chrome控制台输出(包含8616个随机数的巨大数组):

如何将漂亮的JSON格式文本正确地推送到客户端

更新:我刚刚注意到,
process.stdout.write(d)
给了我很好的JSON,
console.info(d)
console.log(d)
都在终端上打印出来:

<Buffer 0a 7b 0a 20 20 22 72 65 73 70 6f 6e 73 65 22 3a 20 
7b 0a 20 20 22 76 65 72 73 69 6f 6e 22 3a 22 30 2e 31 22
2c 0a 20 20 22 74 65 72 6d 73  6f 66 53 65 72 ...>

您遇到的问题是数据是从流返回的。stdout支持流,因此它看起来应该是这样的。另一方面,console.log在每个实例之后附加一个换行符,因此它在将流传输到stdout之前中断流,以便直接写入缓冲区

甚至不用记录每个数据,而是将数据建立到一个变量中,并在结束事件期间处理输出

  var response = '';
  res.on('data', function(d) {
    response += data;
  });
  res.on('end', function(d) {
    console.log(response);
    // now you can do what you need to with it including passing it to the socket
  });

作为替代方案,您可以在浏览器端处理它,在流缓冲区到达后将其转换为字符串,但就我个人而言,我宁愿将该逻辑保留在后端。

您是否尝试过用JSON.stringify()包装您发出的对象?我认为您需要这样做——然后在客户端上使用JSON.parse()将其转换回一个对象。@Catalyst它不起作用。使用这两种JSON方法仍然给了我一些数字,但我确实注意到了一些有趣的事情(参见我的更新)。谢谢!这很有效。我不得不将您的代码更改为:
response+=d。我还使用了
data=JSON.parse(data.weather)来获取我想要的对象。
  var response = '';
  res.on('data', function(d) {
    response += data;
  });
  res.on('end', function(d) {
    console.log(response);
    // now you can do what you need to with it including passing it to the socket
  });