【问题标题】:Parse JSON values from curl command in node.js从 node.js 中的 curl 命令解析 JSON 值
【发布时间】:2012-03-15 22:28:39
【问题描述】:

我可以使用以下代码从 Twitter 获取 JSON 流到客户端:

var command = 'curl -d @tracking https://stream.twitter.com/1/statuses/filter.json -uUsername:Password'

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});

  child = exec(command);

  child.stdout.on('data', function(data) {

  res.write(data);

  });

}).listen(1337, "127.0.0.1");

但我无法从 JSON 中获取 'text' 或 'id' 值。我尝试过使用 jQuery 的 parsJSON() 和其他东西,例如这样的代码:

var command = 'curl -d @tracking https://stream.twitter.com/1/statuses/filter.json -uUsername:password'

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});

  child = exec(command);

  child.stdout.on('data', function(data) {

  for (i=0; i<data.length; i++) {
    reduceJSON = data[i]["text"]
    stringJSON = String(reduceJSON)
    res.write(stringJSON);
}

});

}).listen(1337, "127.0.0.1");

我不断收到“未定义”或“readyStatesetRequestHeadergetAllResponseHeadersgetResponseHeader”或“object:object”的流。有人知道如何获得个人价值吗?

【问题讨论】:

  • 你为什么使用 CURL 和 exec 而不是节点请求库?

标签: json node.js curl


【解决方案1】:

简短的回答是data 是一个字符串,而不是 JSON。您需要缓冲所有数据,直到child 发出“结束”。 end 运行后,您需要使用JSON.parse 将数据转换为 JavaScript 对象。

也就是说,在这里使用 while 单独的 cURL 进程是没有意义的。我会使用request 模块,并执行以下操作:

var request = require('request');
var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});

  var r = request.post(
    'https://stream.twitter.com/1/statuses/filter.json',
    { auth: "Username:Password", 'body': "track=1,2,3,4" },
    function(err, response, body) {
      var values = JSON.parse(body);

      console.log(values);

    }
  );
  r.end();
}).listen(1337, "127.0.0.1");

如果这不起作用,请告诉我。我显然没有用户或密码,所以我无法测试它。

【讨论】:

  • 感谢您的回复。它输出该请求没有方法“结束”。也许是因为响应是连续的流?当我删除 .end() 时,我得到了成功的响应,但是第一个花括号会引发错误,即 {"retweet_count":0,"favorited":false,"text":"Cumbrian pubs could cash in on Sk ^ SyntaxError: Unexpected token { 所以我可能只会使用第三方,但这不利于学习 Node。
  • end 位是错字。我仍然不是 100% 确定你需要它,但试试我现在拥有的。至于解析,打印出body,看看是不是都是合法的JSON。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
  • 2017-04-06
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
相关资源
最近更新 更多