Look at a simple jquery example to traverse a JavaScript array object.
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);});
The code snippet above works fine, prompting "Apple", "orange" ... And so on, as expected.
Problem: JSON string
In the following example, a JSON string (enclosed in single or double quotation marks) is declared directly.
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);});
In Chrome, it shows the error under the console:
Uncaught typeerror:cannot use ' on ' operator to search for ' 156 '
In [{"id": "1", "TagName": "Apple"} ...
Solution: The JSON string is converted to a JavaScript object.
To fix it, convert it to a JavaScript object by using standard Json.parse () or jquery's $.parsejson.
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);});
JQuery $.each traversal JavaScript Array object instance