I have some PHP that generates the a JSON object from data from a MySQL database
$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);
This generates the following JSON object:
[
{"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"}}
]
When receiving it back in Ajax and running it through the following:
$.each(data, function(key, val) {
string =string + "Key: " + key + " Value:" + val + "<br />";
});
which prints the following:
Key: 0 Value:[object Object]
Key: 1 Value:[object Object]
Any ideas about how I can access the objects within key 0 and 1 in data?
This is because Object’s default toString implementation results in “[object Object]” when concatenating to a String object. You can access the fields of the val object as usual, for example:
like this:
Please note that val in the loop above is the {“data”: …} part of the JSON code, that is why you need to specify val.data. to access parts of the address data inside.
Also, you could simply remove the data nesting level, resulting in a JSON layout like that:
Using this PHP code:
And then, you could access the address data fields in the loop like this: