Reputation: 10738
If i have a php file that outputs json data with numerical keys, like
<?php
$array[1] = "abcd";
$array[2] = "efgh";
$array[3] = "1234";
$array[4] = "5678";
echo json_encode($array);
?>
how do i access the value for say key 4? The integer in "data.4" below is breaking the code. Any help would be greatly appreciated. Thanks!
$.ajax({
type: "GET",
url: "http://localhost:8888/myapp/json/json_data",
async: false,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
//$("#box").html(JSON.stringify(data, null, 4));
$("#box").append("<br/>" + data.4)
}
});
Upvotes: 0
Views: 1431
Reputation: 348992
Use brackets to access the property: data['4']
.
Note: Your PHP is not returning an array, but an object: {"1":"abcd","2":"efgh","3":"1234","4":"5678"}
.
PS. You've got a typo in your overrideMimeType
. You shouldn't have to override this though, because you're using jQuery. For an alternative, see $.getJSON
.
Upvotes: 3