0

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)
     }
    });
1
  • Can't do it like this, Nope. Do -> data["4"] Commented Jun 28, 2012 at 21:49

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I should stop responding with my answers in comments. +1!
If the array keys weren't manually set on the php side, json_encode would return an array instead of an object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.