2013-05-12 31 views
0

我收到的錯誤:的JavaScript/Node.js的JSON.parse()來未定義

undefined:1 
'{"completed_in":0.078,"max_id":333655176038719488,"max_id_str":"3336551760387 
^ 
SyntaxError: Unexpected token ' 
    at Object.parse (native) 
    at /home/tweets/10seconds.js:25:25 
    at passBackControl (/home/tweets/node_modules/oauth/lib/oauth.js:367:11) 
    at IncomingMessage.<anonymous> (/home/tweets/node_modules/oauth/lib/oauth.js:386:9) 
    at IncomingMessage.EventEmitter.emit (events.js:117:20) 
    at _stream_readable.js:895:16 
    at process._tickCallback (node.js:415:13) 

當從搜索API解析Twitter的API JSON。

我使用的解析此JSON的代碼是:

MongoClient.connect("mongodb://localhost:27017/db", function(err, db) { 

if(err) { return console.dir(err); } 
    var collection = db.collection("tweets"); 

    while(run < 200){ 

     oa.get("http://search.twitter.com/search.json?q=morning&rpp=100&include_entities=true&result_type=mixed", access_token, access_token_secret, function(error, data) { 
      var theTweets = JSON.parse(sys.inspect(data)); 

      collection.insert(theTweets, {w:1}, function(err, result) {}); 
      console.log(run); 
     }); 
    run = run + 1; 
    } 

}); 

這是什麼原因?

+0

爲什麼你'sys.inspect()'數據'?我期望'data'是JSON,所以你應該只是'JSON.parse(data)',或者它已經是一個原生的JS對象,所以你根本不需要解析它。 – 2013-05-12 18:59:24

+1

@MattBall,heh ...幾乎相同的消息= P – plalx 2013-05-12 18:59:54

回答

0

可能sys.inspect的輸出不是JSON,而是增加了報價'

0

你爲什麼用sys.inspect

如果數據是JSON字符串,然後使用JSON.parse(data);,如果它是一個object已經,那麼你不必使用JSON.parse在所有...

0

的問題是在sys.inspect()調用正如其他答案和評論所述。

隨着文檔的NodeJS(http://nodejs.org/api/util.html#util_util_inspect_object_options)中指出:

Return a string representation of object, which is useful for debugging.

順便說一句,似乎他們改變了SYS模塊名稱UTIL

通過在較舊的節點版本上運行以下代碼,您可以輕鬆地進行小型測試。它應該拋出你的錯誤:

var sys = require('sys'); 
var data = '{"test":1, "test2":2}'; 
sys.puts(JSON.parse(sys.inspect(data))); 

然後刪除sys.inspect調用。它應該正確地解析對象:

var sys = require('sys'); 
var data = '{"test":1, "test2":2}'; 
sys.puts(JSON.parse(data));