0

I have a JSON file containing:

[{
  "title": "title you desire",
  "url" : "thisistheurl.com"
},{
  "title": "title you desire",
  "url" : "thisistheurl.com"
},{
  "title": "title you desire",
  "url" : "thisistheurl.com"
}]

I am now trying to add these into a JS array, and try to show them as an alert on my mobile:

$.getJSON('links.json', function (json) {
    var linkList = [];
    $.each(json, function(i, obj) {
        linkList.push([obj.title, obj.url]);
    });
});

$.each( linkList, function( key, value ) {
  alert( value.title + ": " + value.url );
});

But when I run it on my phone no alerts are shown. Any ideas what I might be doing wrong?

1 Answer 1

1

Try changing

$.each(JSONObject.results.bindings, function(i, obj) {

to

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

Edit: Also, you should be declaring var linkList = [] outside the scope of the $.getJSON function (above it). Otherwise it will be undefined in the global scope.

Edit 2: Oh, even more importantly, $.getJSON is an asynchronous function. What's happening is you're starting to load the .json file, and then your code continues on to the alert part. At this point, it hasn't been loaded yet, so the array is always empty. Then a few milliseconds later, it loads the JSON, it's just too late. Move your $.each code inside the $.getJSON callback.

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

4 Comments

Now something happend (After your second edit). Now I get the 3 alerts, but all of them says "undefined : undefined".
Remove the .value from obj.title and obj.url.
In that case, add this line above linkList.push: console.log(obj);. Then check your console, it will verify what $.getJSON is producing.
Oh whoa never mind, I should've reviewed your code more closely. You're converting the data into an array in your push. Instead, just change your push line to linkList.push(obj);. (Or, you can change the alert line to value[0] and value[1].)

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.