0

I have a PHP file which only return an array with the drivers and a url:

{"drivers":[{"marco":[0],"luigi":[123],"Joan":[2444],"George":[25]}, {"marco":[23],"luigi":[3],"Joan":[244],"George":[234]}],"url":"google.es"}

Is the json correctly structured? And I'm trying to get the result using jQuery and AJAX by this way:

$.getJSON('calculate.php&someparams=123', function(data) {
    alert("url - " + data.url);
    var arr = data.drivers;

    for (var i = 0; i < arr.length; i++) {
        alert(arr[i] + " - " + arr[i][0]);
    }
});

I see the first alert() with the url, but the second one does not works... What am I doing wrong?

If you need more info let me know and I'll edit the post.

mllamazares
  • 7,876
  • 17
  • 61
  • 89
  • _"Is the json correctly structured?"_ Do you mean "is it valid json"? Because the structure looks valid in the sense of not having syntax errors, but whether it is "correct" depends on what you want it to represent. (Though having said that I'd suggest that putting every number in its own array is not necessary unless it is sometimes possible for a name to have more than one number associated with it.) – nnnnnn Apr 27 '13 at 11:47

3 Answers3

1

The drivers is not an array, it is an object, you use $.each to iterate through the object elements.

$.getJSON('calculate.php&someparams=123', function(data) {
    $.each(data.drivers, function(key, value){
        $.each(value, function(key, value){
            console.log(key, value);
        });
    })
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

That's an object, not an array. It has named properties, not numerical indexes.

You need a for in loop to loop over the properties.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

drivers is an object. Not an array.

How about this?

var json_string = '{"drivers":{"marco":[0],"luigi":[123],"Joan":[2444],"George":[25]},"url":"google.es"}';
var obj = jQuery.parseJSON(json_string);
alert(obj.url);
jeyraof
  • 863
  • 9
  • 28