2013-01-06 116 views
2

我想解析一個JSON字符串,但是當我做我得到未定義。Jquery JSON解析返回undefined

var codes = jQuery.parseJSON(response); 

$.each(codes, function (key, value) { 
    alert(value.Display); 
}); 

這裏是上面codes變量的內容:

["{ Display = string1, Sell = string2 }", 
"{ Display = string1, Sell = string2 }"] 

警報返回value.Display作爲undefined。我期待「String1」。我究竟做錯了什麼?

+3

使用http://jsonlint.com驗證JSON – charlietfl

+0

你的解析'codes'值應該是這樣的:'[{ 「顯示」: 「字符串1」, 「賣」: 「字符串2」},{ 「Display」:「string1」,「Sell」:「string2」}]'。 –

回答

3

你不能。數組中沒有Display屬性,它是一個包含兩個字符串的數組。

這些字符串與JSON類似,但不足以被解析。

如果你把字符串遵循JSON標準,你可以在陣列中解析每個項目爲對象,那麼你就可以訪問Display屬性:

var response = '["{ \\"Display\\": \\"string1\\", \\"Sell\\": \\"string2\\" }", "{ \\"Display\\": \\"string1\\", \\"Sell\\": \\"string2\\" }"]'; 

var codes = jQuery.parseJSON(response); 

$.each(codes, function (key, value) { 
    var obj = jQuery.parseJSON(value); 
    alert(obj.Display); 
}); 

演示:http://jsfiddle.net/Guffa/wHjWf/

另外,您可以使整個輸入遵循JSON標準,以便您可以將其解析爲一組對象:

var response = '[{ "Display": "string1", "Sell": "string2" }, { "Display": "string1", "Sell": "string2" }]'; 

var codes = jQuery.parseJSON(response); 
console.log(codes); 
$.each(codes, function (key, value) { 
    alert(value.Display); 
}); 

演示: http://jsfiddle.net/Guffa/wHjWf/1/

+0

今天救了我很多。我不明白爲什麼我必須直到現在才進行雙解析。感謝您的解釋! – Reiion

6

這不是一個有效的JSON字符串。
正確的字符串應該是這樣的:

'{ "Display": "string1", "Sell": "string2" }' 
1

我得到了這個錯誤,無意中json編碼我的數組數據兩次。

像這樣:

$twicefail = '{"penguins" : "flipper"}'; 
return json_encode($twicefail); 

然後在我看來,我把它撿起來是這樣的:

var json_data = jQuery.parseJSON(my_json_response); 

alert(json_data.penguins);  //Here json_data.penguins is undefined because I 
           //json_encoded stuff that was already json. 

更正後的代碼如下:

$twicefail = '{"penguins" : "flipper"}'; 
return $twicefail; 

然後我查看,拿起像這樣:

var json_data = jQuery.parseJSON(my_json_response); 

alert(json_data.penguins);  //json_data.penguins has value 'flipper'.