2017-02-16 42 views
0

我正在執行對返回簡單JSON對象的url的get請求。Node.js中的JSON.parse問題

這裏是網址:http://live.albiononline.com/status.txt

正如你可以看到它是一個文本文件,它的內容類型標題爲text/plain。當我收到的身體日誌,它是:

{ "status": "online", "message": "All good." }

但是當我嘗試登錄,它body.status是不確定的。當我做var data = JSON.parse(body);然後console.log(data.status);我得到:

undefined:1 
{ "status": "online", "message": "All good." } 
^ 

SyntaxError: Unexpected token in JSON at position 0 

任何想法發生了什麼?我認爲它與從.txt文件中提取的事實有關?

UPDATE:

request('http://live.albiononline.com/status.txt', function (error, response, body) { 
      if (!error && response.statusCode == 200) { 
       console.log(body); // { "status": "online", "message": "All good." } 
       console.log(body.status); // undefined 
      } 
     }); 
+0

它已經JSON對象。你不需要解析 – RaR

+0

在我的問題中,我說'但是當我嘗試登錄時,body.status它是未定義的。' – TJH

+0

你可以告訴我你的代碼一次 –

回答

1

的原因是因爲輸出不是字符串化JSON對象,它只是一個普通的字符串。

你的示例代碼的工作,而我得到的輸出:

'{ "status": "online", "message": "All good." }\r\n' 

一個真正的JSON字符串不會有多餘的空格,並在年底轉義字符。

解決方案:

x=x.trim(); // trimming off the \r\n 
var output = JSON.parse(x); // parsing the JSON 
+0

嗯。那麼我如何解析它作爲一個對象呢? – TJH

+0

這是答案,修剪JSON.parse()之前的\ r \ n –

+0

@TJH檢查我編輯的答案 –