0

Simple problem in Jquery - however the solution is not clear to me

$( document ).ready(function() {
    handleJson();
});

function handleJson(){
    $.getJSON("fileList.json", function(json) {

        $.each(json, function(idx, obj) {
            console.log(json.fileurls[idx]);
        });

    });
}

And this is my json

{
  "fileurls":[
    "file y 2014-09-17 10_43_40",
    "file x 2014-09-15 10_15_32"
  ]
}

The printed result in console is undefined

1
  • What does console.log(json); output? Commented Sep 29, 2014 at 15:53

4 Answers 4

1

this doesn't work, because you are calling fileurls[idx], but filurls IS idx. idx is the index of the array, obj is its value.

In your JSON the index of the array is 'fileurls' and it contains the two filenames entries.

To loop through the filenames, you have to loop through the array itself, so you have to add an 2nd each loop. Try this:

function handleJson(){
$.getJSON(fileList.json, function(json) {
    $.each(json, function(idx, obj) {
        $.each(obj, function(idx2, obj2) {
            console.log(obj2);
        });
    });
});

}

Good luck Boulder

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

Comments

0

You do not need to iterate if want to access index wise, just write like this:

$.getJSON("fileList.json", function(json) {

        console.log(json.fileurls[0]);

    });

Your array is json.fileurls, json is single object so iterate on json.fileurls :

$.each(json.fileurls, function(idx, obj) {

            console.log(json.fileurls[idx]);
        });

Running Example:

http://jsfiddle.net/5jo87475/

Comments

0

The problem is likely due to the fact you are trying to loop each property of the json object, rather than the fileurls array. Try this:

.each(json.fileurls, function(idx, obj) {
    console.log(json.fileurls[idx]);
});

Though the obj argument is actually the value you want already, so you could make it easier like so:

.each(json.fileurls, function(idx, obj) {
    console.log(obj);
});

Comments

0

The OBJ will give you just "fileurls" but if you want to have the "file y 2014-09-17 10_43_40" and "file x 2014-09-15 10_15_32" elements separately you should iterate over OBJ again

$.getJSON("fileList.json", function(json) {

     $.each(json, function(idx, obj) {

          $.each(obj, function(count, element) {

               console.log(element);

          });
     });
});

Comments

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.