json对象中有多个json对象

时间:2012-09-11 08:25:19

标签: php mysql ajax json

我有一些PHP从MySQL数据库中的数据生成JSON对象

$addressData = mysql_query("SELECT * FROM address WHERE ContactID = $contactID")or  die("<br/><br/>".mysql_error());

while($r = mysql_fetch_assoc($addressData)){
    $rows[] = array('data' => $r);
}

// now all the rows have been fetched, it can be encoded
echo json_encode($rows);

这将生成以下JSON对象:

[
  {"address":
    {"AddressID":"10011","AddressType":"Delivery","AddressLine1":"4 Caerleon Drive","AddressLine2":"Bittern","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 5LF","Country":"United Kingdom","ContactID":"10011"}},
  {"address":
    {"AddressID":"10012","AddressType":"Home","AddressLine1":"526 Butts Road","AddressLine2":"Sholing","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"}}
]

在Ajax中接收它并通过以下方式运行它时:

$.each(data, function(key, val) {
  string =string + "Key: " + key + " Value:" + val + "<br />";
});

打印以下内容:

  

键:0值:[对象对象]

     

键:1值:[object Object]

有关如何访问数据中01项内对象的任何想法?

2 个答案:

答案 0 :(得分:2)

这是因为在连接到String对象时,Object的默认toString实现会导致“[object Object]”。您可以照常访问val对象的字段,例如:

val.data.AddressID
像这样:

$.each(data, function(key, val) {
  string += "Key: " + key + " Value:" + val.data.AddressID + "<br />";
});

请注意,上面循环中的val是JSON代码的{“data”:...}部分,这就是为什么需要指定 val.data。来访问部分里面的地址数据。

此外,您只需删除数据嵌套级别,即可生成类似的JSON布局:

[
    {"AddressID":"10011","AddressType":"Delivery","AddressLine1":"4 Caerleon Drive","AddressLine2":"Bittern","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 5LF","Country":"United Kingdom","ContactID":"10011"},
    {"AddressID":"10012","AddressType":"Home","AddressLine1":"526 Butts Road","AddressLine2":"Sholing","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"}
]

使用此PHP代码:

while($r = mysql_fetch_assoc($addressData)){
    $rows[] = $r;
}

然后,您可以像这样访问循环中的地址数据字段:

$.each(data, function(key, address) {
  string += "Key: " + key + " Value:" + address.AddressID + "<br />";
});

答案 1 :(得分:1)

我会改变你的json的布局,你不需要嵌套。尝试:

[
    {"AddressID":"10011","AddressType":"Delivery",...},
]

然后你可以使用key =&gt;将返回值迭代为数组val val将成为对象,因为现在,val是保存所需对象的对象...