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 with single or double quotes) 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 displays the following error in the console:
Uncaught typeerror:cannot use "in" 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 through standard Json.parse () or $.parsejson of jquery.
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);
});