php - jQuery: How to iterate through JSON encoded string (array) -


i jquery beginner , hope can me , provide me explanations.

i have ajax call returns json encoded string 2 values each item, itemid , itemval - an example looks follows (using console.log):

console.log(data) result:

string(225) "[{"itemid":1,"itemval":"china"},{"itemid":2,"itemval":"france"},{"itemid":3,"itemval":"germany"},{"itemid":4,"itemval":"italy"},{"itemid":5,"itemval":"poland"},{"itemid":6,"itemval":"russia"},{"itemid":7,"itemval":"usa"},...]" 

the number of items here varies if itemid listed there corresponding itemval.
itemid unique integer, itemval plain text.

everything works far here comes problem:
for each itemid here have corresponding itemval, e.g. log console or alert testing.

i know there various approaches jquery.each, $.each, for, foreach etc. since started not sure how can iterate through resp. how can select single itemids it.

i tried different approaches, incl. $.parsejson(data) failed , seems problem input before being decoded two-dimensional array instead of one-dimensional one (i hope using right terms here) caused them either return error or alert every single character of string.

update - failing example per answer below

$.ajax({             type: "post",        url: "ajax.php",     cache: "false",     data: {         node: 'fetchcountries',         itemids: itemids // list of integers     },     success: function(data){         console.log(data);         var arr = json.parse(data);         $.each($(arr),function(key,value){            console.log(value.itemval);         });     } }); 

update 2 - php:

case "fetchcountries":     $intval_itemids = array_map("intval", $_post["itemids"]);     $itemids = implode(",", $intval_itemids);      $stmt = $conn->prepare("select itemid, en countries itemid in(" . $itemids . ") order itemid");     $stmt->execute();     $result = $stmt->get_result();     while($arrcountries = $result->fetch_assoc()){         $countries[] = array("itemid" => $arrcountries["itemid"], "itemval" => $arrcountries["en"]);     }     var_dump(json_encode($countries));     break; 

expected outcome (for testing):

console.log("china"); console.log("france"); console.log("germany"); // ... 

can me ?

many thanks, tim

you have json string representing array, parsing actual array. looping through array, pushing each element new array (arr).

perhaps there confusion. this shed light.

// considering following json string: var data = '[{"itemid":1,"itemval":"china"},{"itemid":2,"itemval":"france"},{"itemid":3,"itemval":"germany"},{"itemid":4,"itemval":"italy"},{"itemid":5,"itemval":"poland"},{"itemid":6,"itemval":"russia"},{"itemid":7,"itemval":"usa"}]';  // can create array so: var thearray = json.parse(data);  // have array each item being `object` // "itemid" , "itemval".  can loop through // array , @ each object so: thearray.foreach(function (obj) {     console.log(obj.itemid + ': ' + obj.itemval); }); 

Comments