jQuery:如何遍历JSON编码的字符串(数组)

时间:2021-11-11 15:26:31

I am a jQuery beginner and hope someone can help me with this and also provide me some explanations.

我是一个jQuery初学者,希望有人可以帮助我,并提供一些解释。

I have an Ajax call that returns a JSON encoded string with two values for each item, an itemID and an itemVal - an example looks as follows (using console.log):

我有一个Ajax调用,它返回一个JSON编码的字符串,每个项有两个值,一个itemID和一个itemVal - 一个例子如下所示(使用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 but if an itemID is listed than there is always a corresponding itemVal.
itemID is a unique integer, itemVal is plain text.

此处的项目数量有所不同,但如果列出了itemID,则始终存在相应的itemVal。 itemID是唯一的整数,itemVal是纯文本。

Everything works so far but here comes my problem:
For each itemID here I have to do something with the corresponding itemVal, e.g. say just log it to the console or alert it for testing.

到目前为止一切都工作但是我的问题出现了:对于每个itemID,我必须对相应的itemVal做一些事情,例如:说只需将其登录到控制台或提醒它进行测试。

I know there are various approaches for this like jQuery.each, $.each, for, foreach etc. but since I just started recently I am not sure how I can iterate through this resp. how I can select the single itemIDs from it.

我知道有各种各样的方法,比如jQuery.each,$ .each,for,foreach等。但是因为我刚刚开始,所以我不知道如何迭代这个resp。我如何从中选择单个itemID。

I tried different approaches, incl. $.parseJSON(data) which failed and it seems the problem is that my input before being decoded is a two-dimensional array instead of a one-dimensional one (I hope I am using the right terms here) which caused them to either return an error or to alert every single character of my string.

我尝试了不同的方法,包括。 $ .parseJSON(数据)失败了,似乎问题是我的输入在解码之前是一个二维数组而不是一维数组(我希望我在这里使用正确的术语)导致它们返回错误或警告我的字符串的每个字符。

Update - failing example as per the answer below

更新 - 根据以下答案的失败示例

$.ajax({        
    type: "post",   
    url: "ajax.php",
    cache: "false",
    data: {
        node: 'fetchCountries',
        itemIDs: itemIDs // a 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 - My PHP:

更新2 - 我的PHP:

case "fetchCountries":
    $intval_itemIDs = array_map("intval", $_POST["itemIDs"]);
    $itemIDs = implode(",", $intval_itemIDs);

    $stmt = $conn->prepare("SELECT itemID, en FROM Countries WHERE itemID IN(" . $itemIDs . ") ORDER BY 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 someone help me with this ?

有人可以帮我弄这个吗 ?

Many thanks, Tim

非常感谢,蒂姆

5 个解决方案

#1


1  

You have a JSON string representing an Array, which you are parsing into an actual Array. Then you are looping through the array, pushing each element into a new Array (arr).

您有一个表示数组的JSON字符串,您将其解析为实际的数组。然后循环遍历数组,将每个元素推送到一个新的数组(arr)。

Perhaps there is some confusion. Hopefully this will shed some light.

也许有一些混乱。希望这会有所启发。

// Considering the 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"}]';

// You can create an Array from this like so:
var theArray = JSON.parse(data);

// Now you have an array with each item being an `object`
// with an "itemId" and an "itemVal".  You can loop through
// this array and look at each object like so:
theArray.forEach(function (obj) {
    console.log(obj.itemID + ': ' + obj.itemVal);
});

#2


1  

WhistleBlower, I have tested your code on my browser. It worked. Why don't you use header("Content-type :application/json"); too. So, you will not have to parse your JSON string.

WhistleBlower,我在浏览器上测试了你的代码。有效。你为什么不用header(“Content-type:application / json”);太。因此,您不必解析您的JSON字符串。

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"}]';
var arr = JSON.parse(data);
$.each($(arr),function(key,value){
   console.log(value.itemVal);
});

#3


0  

As simple as this!

就这么简单!

$.each($(data),function(key,value){
   console.log(value.itemVal); //place alert if you want instead of console.log
});

iterate through the obtained result and get itemVal value of each item

迭代获得的结果并获取每个项目的itemVal值

DEMO HERE


UPDATE

Add dataType option to your ajax and return type from php should be json and I hope you are doing that!

将dataType选项添加到你的ajax并从php返回类型应该是json,我希望你这样做!

$.ajax({        
    type: "POST",   
    url: "ajax.php",
    cache: "false",
    dataType:'json', //Add this
    data: {
        node: 'fetchCountries',
        itemIDs: itemIDs // a list of integers
    },
    success: function(data){
        console.log(data);
        var arr = JSON.parse(data);
        $.each($(arr),function(key,value){
           console.log(value.itemVal);
        });
    }
});

and return from your php should be echo json_encode(result);

并从你的PHP返回应该是echo json_encode(结果);

#4


0  

You're not parsing a string, you're parsing an already-parsed object

你没有解析一个字符串,你正在解析一个已经解析过的对象

just use it directly

直接使用它

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"}];

    $.each(data,function(key,value){
        console.log(value.itemVal);
    });

or/

 var arr = JSON.parse(JSON.stringify(data));

    $.each(arr, function (key, value) {
        console.log(value.itemVal);
    });

Update 1:

I think so your php file like

我想你的php文件就好

    <?php 
      $array = array( array( 'itemID' => 1, 'itemVal' => 'India'), array( 'itemID' => 2, 'itemVal' => 'usa'), array( 'itemID' => 3, 'itemVal' => 'china'), array( 'itemID' => 4, 'itemVal' => 'uk'));
        echo json_encode($array);
//[{"itemID":1,"itemVal":"India"},{"itemID":2,"itemVal":"usa"},{"itemID":3,"itemVal":"china"},{"itemID":4,"itemVal":"uk"}]
     ?>

your script should be

你的脚本应该是

  $.getJSON( "your.php", function( data ) {
              console.log(data);
                $.each(data, function (key, value) {
                    console.log(value.itemVal);
                });
            });

OR

  $.ajax({        
          type: "post",   
          url: "your.php",
          cache: "false",
          dataType: 'json',
          data: {
              node: 'fetchCountries',
              itemIDs: youval // a list of integers
          },
          success: function(data){
              console.log(data);
                var arr = JSON.parse(JSON.stringify(data));
              $.each($(arr),function(key,value){
                 console.log(value.itemVal);
              });
          }
      });

OR

    $.ajax({        
      type: "post",   
      url: "your.php",
      cache: "false",
      dataType: 'json',
      data: {
          node: 'fetchCountries',
          itemIDs: youval // a list of integers
      },
      success: function(data){
          console.log(data);
          $.each($(data),function(key,value){
             console.log(value.itemVal);
          });
      }
  });

#5


0  

Thanks to everyone for the help with this.

感谢大家对此的帮助。

Since all other approaches made sense to me but still failed I did some more research on this and finally found what was causing this.

由于所有其他方法对我来说都是有意义的,但仍然失败了,我对此进行了更多的研究,最后找到了导致这种情况的原因

The issue was indeed on the PHP side and the accepted answer on the following post did the trick - since I added this to my PHP everything else on the JS side is working fine and I don't even need the dataType: "JSON" there:

这个问题确实存在于PHP方面,接下来的帖子上接受的答案就是诀窍 - 因为我把它添加到了我的PHP,JS方面的其他一切工作正常,我甚至不需要dataType:“JSON”那里:

dataType: "json" won't work

dataType:“json”无效

As per this post the solution for my case is the following - kudos to Jovan Perovic:

根据这篇文章,我的案例的解决方案如下 - 对Jovan Perovic的赞誉:

<?php
//at the very beginning start output buffereing
ob_start();

// do your logic here

// right before outputting the JSON, clear the buffer.
ob_end_clean();

// now print
echo json_encode(array("id" => $realid, "un" => $username, "date" => $date));
?>

Thanks again.

#1


1  

You have a JSON string representing an Array, which you are parsing into an actual Array. Then you are looping through the array, pushing each element into a new Array (arr).

您有一个表示数组的JSON字符串,您将其解析为实际的数组。然后循环遍历数组,将每个元素推送到一个新的数组(arr)。

Perhaps there is some confusion. Hopefully this will shed some light.

也许有一些混乱。希望这会有所启发。

// Considering the 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"}]';

// You can create an Array from this like so:
var theArray = JSON.parse(data);

// Now you have an array with each item being an `object`
// with an "itemId" and an "itemVal".  You can loop through
// this array and look at each object like so:
theArray.forEach(function (obj) {
    console.log(obj.itemID + ': ' + obj.itemVal);
});

#2


1  

WhistleBlower, I have tested your code on my browser. It worked. Why don't you use header("Content-type :application/json"); too. So, you will not have to parse your JSON string.

WhistleBlower,我在浏览器上测试了你的代码。有效。你为什么不用header(“Content-type:application / json”);太。因此,您不必解析您的JSON字符串。

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"}]';
var arr = JSON.parse(data);
$.each($(arr),function(key,value){
   console.log(value.itemVal);
});

#3


0  

As simple as this!

就这么简单!

$.each($(data),function(key,value){
   console.log(value.itemVal); //place alert if you want instead of console.log
});

iterate through the obtained result and get itemVal value of each item

迭代获得的结果并获取每个项目的itemVal值

DEMO HERE


UPDATE

Add dataType option to your ajax and return type from php should be json and I hope you are doing that!

将dataType选项添加到你的ajax并从php返回类型应该是json,我希望你这样做!

$.ajax({        
    type: "POST",   
    url: "ajax.php",
    cache: "false",
    dataType:'json', //Add this
    data: {
        node: 'fetchCountries',
        itemIDs: itemIDs // a list of integers
    },
    success: function(data){
        console.log(data);
        var arr = JSON.parse(data);
        $.each($(arr),function(key,value){
           console.log(value.itemVal);
        });
    }
});

and return from your php should be echo json_encode(result);

并从你的PHP返回应该是echo json_encode(结果);

#4


0  

You're not parsing a string, you're parsing an already-parsed object

你没有解析一个字符串,你正在解析一个已经解析过的对象

just use it directly

直接使用它

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"}];

    $.each(data,function(key,value){
        console.log(value.itemVal);
    });

or/

 var arr = JSON.parse(JSON.stringify(data));

    $.each(arr, function (key, value) {
        console.log(value.itemVal);
    });

Update 1:

I think so your php file like

我想你的php文件就好

    <?php 
      $array = array( array( 'itemID' => 1, 'itemVal' => 'India'), array( 'itemID' => 2, 'itemVal' => 'usa'), array( 'itemID' => 3, 'itemVal' => 'china'), array( 'itemID' => 4, 'itemVal' => 'uk'));
        echo json_encode($array);
//[{"itemID":1,"itemVal":"India"},{"itemID":2,"itemVal":"usa"},{"itemID":3,"itemVal":"china"},{"itemID":4,"itemVal":"uk"}]
     ?>

your script should be

你的脚本应该是

  $.getJSON( "your.php", function( data ) {
              console.log(data);
                $.each(data, function (key, value) {
                    console.log(value.itemVal);
                });
            });

OR

  $.ajax({        
          type: "post",   
          url: "your.php",
          cache: "false",
          dataType: 'json',
          data: {
              node: 'fetchCountries',
              itemIDs: youval // a list of integers
          },
          success: function(data){
              console.log(data);
                var arr = JSON.parse(JSON.stringify(data));
              $.each($(arr),function(key,value){
                 console.log(value.itemVal);
              });
          }
      });

OR

    $.ajax({        
      type: "post",   
      url: "your.php",
      cache: "false",
      dataType: 'json',
      data: {
          node: 'fetchCountries',
          itemIDs: youval // a list of integers
      },
      success: function(data){
          console.log(data);
          $.each($(data),function(key,value){
             console.log(value.itemVal);
          });
      }
  });

#5


0  

Thanks to everyone for the help with this.

感谢大家对此的帮助。

Since all other approaches made sense to me but still failed I did some more research on this and finally found what was causing this.

由于所有其他方法对我来说都是有意义的,但仍然失败了,我对此进行了更多的研究,最后找到了导致这种情况的原因

The issue was indeed on the PHP side and the accepted answer on the following post did the trick - since I added this to my PHP everything else on the JS side is working fine and I don't even need the dataType: "JSON" there:

这个问题确实存在于PHP方面,接下来的帖子上接受的答案就是诀窍 - 因为我把它添加到了我的PHP,JS方面的其他一切工作正常,我甚至不需要dataType:“JSON”那里:

dataType: "json" won't work

dataType:“json”无效

As per this post the solution for my case is the following - kudos to Jovan Perovic:

根据这篇文章,我的案例的解决方案如下 - 对Jovan Perovic的赞誉:

<?php
//at the very beginning start output buffereing
ob_start();

// do your logic here

// right before outputting the JSON, clear the buffer.
ob_end_clean();

// now print
echo json_encode(array("id" => $realid, "un" => $username, "date" => $date));
?>

Thanks again.