Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
 
"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 at 11:47

3 Answers

up vote 1 down vote accepted

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);
        });
    })
});
share|improve this answer
 
thanks! but sorry, i've updated the json of the main post... what it would be then? –  Candil Apr 27 at 11:37
 
@Joëlle what is the output you are looking for –  Arun P Johny Apr 27 at 11:37
 
ok! thats it! really thanks! –  Candil Apr 27 at 11:44

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.

share|improve this answer

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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.