2013-12-18 39 views
7

解析文件時,我不明白什麼地方出了錯:語法錯誤:JSON解析錯誤:意外的標識 「對象」(匿名函數)

{ "t": -9.30, "p": 728.11, "h": 87.10 } 

javascript代碼:

<script type="text/javascript"> 
function check() { 
    $.get("http://....file.json", function(response, status, xhr) { 
     if (status == "success") { 
      var json = JSON.parse(response); 
      $("#temp").html(json.t + "&deg;"); 
      $("#pressure").html(json.p + " mm hg"); 
     } 
     if (status == "error") { 
      $("#temp").html("error"); 
     } 
    }); 
} 

我收到錯誤:

SyntaxError: JSON Parse error: Unexpected identifier "object" 
+0

console.log(response); ? –

+1

你不需要解析 – anand4tech

+0

謝謝大家,問題解決了 – aspire89

回答

20

很可能您的response已經是JavaScript對象,它不需要b解析。

刪除行var json = JSON.parse(response);和您的代碼應該工作。

+0

如果mime類型被正確發送,那是肯定的。 –

+0

@dystroy我只是希望服務器管理員是不是愚蠢的改變'.json'文件的MIME:)' – VisioN

+0

比做一個檢查,如果它是一個對象或使用$ .ajax並告訴它它是什麼成爲... – epascarello

5

據對$.ajax jQuery的文檔(這是什麼$.get內部使用):

dataType: ...If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object...)

因此,你的反應很可能已經是一個對象。當你這樣做JSON.parse(response),你真的做

JSON.parse("[object Object]") 

因爲JSON.parse coerces its argument to a string,並且默認平原對象字符串化到[object Object]。初始的[帶領JSON.parse期望一個數組,但它然後扼殺object令牌,它不符合JSON語法。

刪除JSON.parse行,因爲response已被jQuery解析爲一個對象。

相關問題