2012-02-25 94 views
2

我能夠從Twitter獲取JSON流到客戶端使用此代碼:解析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"); 

,但我不能讓「文本」或' ID'值來自JSON。我已經使用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」或流「的對象:對象」。任何人都知道如何獲得個人價值觀?

+0

爲什麼使用CURL和exec代替節點請求庫? – loganfsmyth 2012-02-26 01:45:35

回答

4

簡短的回答是,data是一個字符串,而不是JSON。您需要緩衝所有數據,直到child發出'結束'。在結束運行後,您需要使用JSON.parse將數據轉換爲JavaScript對象。

這就是說,使用一個單獨的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"); 

讓我知道這完全不是那麼回事。我顯然沒有用戶名或密碼,所以我無法測試它。

+0

感謝您的回覆。它輸出的請求沒有方法'結束'。也許是因爲響應是連續的流?當我刪除.end()時,我得到了一個成功的響應,但第一個大括號引發了一個錯誤,例如'{「retweet_count」:0,「favorited」:false,「text」:「Cumbrian酒吧可以在Sk ^ SyntaxError:意外的標記{'所以我可能只是使用第三方,但這不利於學習節點 – EHNole 2012-02-27 16:24:03

+0

'結束'位是一個錯字,我仍然不是100%確定你需要它,但試試我現在,至於解析,打印'body'並查看它是否全部是有效的JSON。 – loganfsmyth 2012-02-27 18:17:26