$.each遍歷json對象

查看一個簡單的jQuery的例子來遍歷一個JavaScript數組對象。html

var json = [ {"id":"1","tagName":"apple"}, {"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"}, {"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"} ]; $.each(json, function(idx, obj) { alert(obj.tagName); });

上面的代碼片段工做正常,提示 「apple」, 「orange」 … 等,如預期同樣。json

問題: JSON 字符串

下面的例子中,聲明瞭一個JSON字符串(隨附單或雙引號)直接地。數組

var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"}]'; $.each(json, function(idx, obj) { alert(obj.tagName); });

 

在Chrome中,它顯示在控制檯下面的錯誤:app

Uncaught TypeError: Cannot use 'in' operator to search for '156' 
in [{"id":"1","tagName":"apple"}...

解決方案:JSON字符串轉換爲JavaScript對象。
要修復它,經過標準JSON.parse()或jQuery 的 $.parseJSON 將其轉換爲JavaScript對象。spa

var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"}]'; $.each(JSON.parse(json), function(idx, obj) { alert(obj.tagName); }); //or 
 $.each($.parseJSON(json), function(idx, obj) { alert(obj.tagName); });
相關文章
相關標籤/搜索