2012-10-15 7 views
1

我一直在這個問題上,我搜索了在網絡和計算器的解決方案,但我不能得到什麼錯誤完全吻合。JSON解析錯誤使用Ajax應答串

這是通過Ajax調用來自服務器的JSON字符串。

{root:{name: "root",description: "root description",checked: false,1:{name: "item1",description: "item1 description",checked: true,1.1:{name: "item1.1",description: "item1.1 description",checked: true}}, 2:{name: "item2",description: "item2 description",checked: true}}} 

使用下面的代碼,我收到後弦xmlhttp.readyState == 4 && xmlhttp.status == 200

var aData; 
     try{ 
     aData =JSON.parse(xmlhttp.responseText); 
     } 
     catch(err){ 
     alert(err); 
     } 

它顯示像

Json.parse expected property name or '}' 

但如果使用eval()函數的錯誤它工作正常

var aData; 
     try{ 
     aData =eval('(' + xmlhttp.responseText + ')'); 
     } 
     catch(err){ 
     alert(err); 
     } 

請exaplin這裏的錯誤是什麼。

謝謝。

編輯:

我檢查了json查看器中的字符串,它的工作正常。 http://jsonviewer.stack.hu/「> JSON view

+6

嗯,這不是有效的JSON。鍵必須用雙引號。請參閱http://json.org/和http://jsonlint.com/。這是一個有效的JS對象字面值,這就是'eval'工作的原因。的 –

+0

可能重複[阿賈克斯JSON解析錯誤](http://stackoverflow.com/questions/3428329/ajax-json-parse-error) –

+0

我猜你不能打電話給你的項目1,2等作爲這些在javascript中不是有效的變量名稱。 –

回答

-1

那是因爲這是無效的JSON,你不能用數字作爲鍵名,因此,你可以跳過的數字或把它們放在引號,使他們「弦」

校驗輸出和固定JSON低於:

固定JSON:

{ 
    "root":{ 
     "name":"root", 
     "description":"root description", 
     "checked":false, 
     "1":{ 
     "name":"item1", 
     "description":"item1 description", 
     "checked":true, 
     "1.1":{ 
      "name":"item1.1", 
      "description":"item1.1 description", 
      "checked":true 
     } 
     }, 
     "2":{ 
     "name":"item2", 
     "description":"item2 description", 
     "checked":true 
     } 
    } 
} 

驗證輸出:

Error:Strings should be wrapped in double quotes.[Code 17, Structure 2] 
Error:Strings should be wrapped in double quotes.[Code 17, Structure 5] 
Error:Strings should be wrapped in double quotes.[Code 17, Structure 9] 
Error:Strings should be wrapped in double quotes.[Code 17, Structure 13] 
Error:Expecting string, not number.[Code 8, Structure 17] 
Error:Expecting comma or }, not colon.[Code 13, Structure 18] 
Error:Strings should be wrapped in double quotes.[Code 17, Structure 20] 
Error:Strings should be wrapped in double quotes.[Code 17, Structure 24] 
Error:Strings should be wrapped in double quotes.[Code 17, Structure 28] 
Error:Expecting string, not number.[Code 8, Structure 32] 
Error:Expecting comma or }, not colon.[Code 13, Structure 33] 
Error:Strings should be wrapped in double quotes.[Code 17, Structure 35] 
Error:Strings should be wrapped in double quotes.[Code 17, Structure 39] 
Error:Strings should be wrapped in double quotes.[Code 17, Structure 43] 
Error:Expecting string, not number.[Code 8, Structure 49] 
Error:Expecting comma or }, not colon.[Code 13, Structure 50] 
Error:Strings should be wrapped in double quotes.[Code 17, Structure 52] 
Error:Strings should be wrapped in double quotes.[Code 17, Structure 56] 
Error:Strings should be wrapped in double quotes.[Code 17, Structure 60]