2013-02-18 124 views
1

我正在一個錯誤的頁面上與另一頁上完美的作品代碼...這就是:jQuery的:神祕的JSON解析錯誤

$.each(json,function(index,element){ 
var tr = $("<tr>").appendTo($tabbody); 
$(tr).append('<td><a target="_blank" href="forum.php?t='+element.topic_id+'">'+element.topic_nom+"</a></td>"+'<td>'+element.date_heure+"</td>"); 
}); 

JSON是在一個GET請求的結果PHP頁面:

$data = $query->fetchAll(PDO::FETCH_ASSOC); 
echo json_encode($data); 

結果的爲例:

[ 
    { 
    "topic_nom": "Deuxième question de linterro manip 5", 
    "topic_id": "1", 
    "user_nick": "Symael", 
    "user_id": "1", 
    "msg_id": "10", 
    "date_heure": "2013-02-17 18:28:04" 
    }, 
    { 
    "topic_nom": "Quel est le sens de la vie ?", 
    "topic_id": "2", 
    "user_nick": "Symael", 
    "user_id": "1", 
    "msg_id": "10", 
    "date_heure": "2013-02-17 18:28:04" 
    } 
] 

這是有效的JSON ...我得到的錯誤是:

TypeError: invalid 'in' operand e 
...ute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r... 

如果我嘗試$ .parseJSON(json); :

SyntaxError: JSON.parse: unexpected character 
...ute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r... 

當我確認我的Json上http://jsonlint.com/結果是:

Parse error on line 1: 
[ {  "to 
^ 
Expecting '{', '[' 

如果手動改寫第一[它突然變得有效。 我想我是這裏一個非常奇怪的故障的受害者,有人能幫助我嗎? Oo


下面是解決方案,請參閱Stoive的解釋答案。

obj = $.parseJSON(json.trim()); 
    $.each(obj,function(index,element){ 
     var tr = $("<tr>").appendTo($tabbody); 
     $(tr).append('<td><a target="_blank" href="forum.php?t='+element.topic_id+'">'+element.topic_nom+"</a></td>"+'<td>'+element.date_heure+"</td>"); 
    }); 
+1

「有效的JSON」對我說jsonlint。 – sigod 2013-02-18 00:33:04

+0

你可能在你的數據之前有一些不可見的字符 – Musa 2013-02-18 00:38:10

+0

它是有效的「有效的JSON」 – 2013-02-18 00:39:43

回答

4

很多時候,在byte order mark可以潛入保存在編輯器如記事本文件。

嘗試在0位置和console.log結果獲取的json的字符代碼:

console.log(json.charCodeAt(0).toString(16)); 

你應該得到5b作爲結果,而不是像feff。如果是這種情況,那麼JSON.parse(json.trim())可以通過刪除不可見的空白字符來提供幫助。

+0

「getCharCodeAt不是函數」? ^^ 但$ .parseJSON(json.trim())正常工作! 非常感謝,我不會找到它Oo – Symael 2013-02-18 01:03:05

+0

我應該爲所有的php文件選擇「UTF-8(無BOM)」編碼嗎? – Symael 2013-02-18 01:12:56

+0

沒問題!我的錯,現在是'charCodeAt',現在已經糾正。沒有BOM的UTF-8是JSON文件的正確字符編碼。我對PHP並不熟悉,因此在創建JSON字符串時,必須檢查它是否寫入BOM。 – Stoive 2013-02-18 02:02:52