在$ .each中获取输出json

时间:2011-12-23 20:26:55

标签: javascript jquery json

我的json数据是:

{
   "guide":0,
   "reunits":[
      {
         "residence":[
            {
               "name_re":"THE PORT",
               "id":"88aa355ca54853640929c25c33613528"
            }
         ]
      },
      {
         "residence":[
            {
               "name_re":"KECIK",
               "id":"2843543fa45857d92df3de222938e84a"
            }
         ]
      },
      {
         "residence":[
            {
               "name_re":"GREEN ANKA",
               "id":"fe585cc4b4dfff1325373728929e8af9"
            }
         ]
      }
   ]
}

如何在jquery中通过name_re在json数据中完成警报,值ideach

我的尝试:

$.each(data.reunits, function (index, value) {
    alert(value.residence.name_re); // this don't output.
})

5 个答案:

答案 0 :(得分:3)

residence是一个数组([]),它只有一个元素,一个具有name_re属性的对象。

alert(value.residence[0].name_re);

jsFiddle Demo

答案 1 :(得分:2)

这是因为它们在阵列中。您需要为每个索引访问索引0:

$.each(data.reunits, function(index, value) {
    alert(value.residence[0].name_re);
});

答案 2 :(得分:1)

住所是一个数组,因此您必须执行以下js fiddle

    $(document).ready(function() {
        var data = {
            "guide": 0,
            "reunits": [
                {
                "residence": [
                    {
                    "name_re": "THE PORT",
                    "id": "88aa355ca54853640929c25c33613528"}
                ]},
            {
                "residence": [
                    {
                    "name_re": "KECIK",
                    "id": "2843543fa45857d92df3de222938e84a"}
                ]},
            {
                "residence": [
                    {
                    "name_re": "GREEN ANKA",
                    "id": "fe585cc4b4dfff1325373728929e8af9"}
                ]}
            ]
        };
        $.each(data.reunits, function() {
            $.each(this.residence, function() {
                alert(this.name_re);
                alert(this.id);
            });
        });
    });

答案 3 :(得分:0)

var data = JSON;
var reunits = data.reunits;
for (var i = 0, len = reunits.length; i < len; i++) {
    alert(reunits[i].residence[0].name_re);
}

答案 4 :(得分:0)

value.residence是一个数组。它应该是value.residence[0].name_re

$.each(data.reunits, function (index, value) {
    alert(value.residence[0].name_re);
})