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

How do I assign a javascript array to that of an array of objects from an EXTERNAL json file?

Here's what I've tried.

JavaScript Snippet

var i = 0;
var testjson = $.getJSON('/TestJSON');
jsonObj = JSON.parse(testjson);

$("#testJSONBtn").click(function () {
    while (i <= jsonObj.events.length) {
        $("#JSONOutput").append(jsonObj.events[i].title + ", " + jsonObj.events[i].date + ", " + jsonObj.events[i].explanation + "<br/>")
        i += 1;
    }
});

JSON File Contents

{
"events":
[
    {"title":"Okmulgee Public Schools Starts 3rd Quarter" , "date":"1-2-2013" , "explanation":"Okmulgee Public Schools begins its third quarter."}
    {"title":"Okmulgee Public Schools-Closed in Observance of Martin Luther King Jr. Holiday" , "date":"1-21-2013" , "explanation":"The Okmulgee Public Schools will be closed in observance of the Martin Luther King Jr. holiday."}
    {"title":"Okmulgee Public Schools County Professional Day" , "date":"2-1-2013" , "explanation":"Okmulgee Public Schools County Professional Day is today."}
]
}

What am I doing wrong?

share|improve this question
1  
For the record, $.getJSON is an ajax call. –  Snuffleupagus Jan 2 at 20:32
1  
... And it is asynchronous and does not return JSON. You must do something with it in the success handler –  Michael Berkowski Jan 2 at 20:32
1  
Did you read the documentation by now: api.jquery.com/jQuery.getJSON? Why did you delete the previous question? –  Felix Kling Jan 2 at 20:33
3  
@VoidKing: That's how Ajax works. Receiving the data from an external URL is a non-blocking process. Once the data is received, your code is notified by calling the provided callback. It has nothing to do with JSON itself. Imagine you send your assistant to pick something up from a store. Are you just standing around and wait until he comes back? I assume you continue with your work until he comes back and then deal with whatever he picked up. –  Felix Kling Jan 2 at 20:36
3  
@VoidKing Here are some good resources. Please take some time to review them. They do not answer your immediate question but they will likely answer some future questions you will have (like you mentioned you're new and learning). Cheers. Remember; crawl before you run. –  rlemon Jan 2 at 20:55
show 12 more comments

closed as not a real question by VoidKing, Neal, rlemon, bensiu, Troy Alford Jan 3 at 0:59

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

3 Answers

up vote 4 down vote accepted

AJAX functions do not have data return values, they just return an AJAX object.

You need to use callbacks.

Try this:

$.getJSON('/TestJSON', function(jsonObj){
    $("#testJSONBtn").click(function () {
        for(var i = 0; i < jsonObj.events.length; ++i) {
            $("#JSONOutput").append(jsonObj.events[i].title + ", " + jsonObj.events[i].date + ", " + jsonObj.events[i].explanation + "<br/>")
        }
    });
});

Better:

var btn = $("#testJSONBtn"); //cache the element
var output = $("#JSONOutput"); // ^^^
$.getJSON('/TestJSON', function(jsonObj){
    btn.click(function () {
        var val = "";
        for(var i = 0; i < jsonObj.events.length; ++i) {
            val += jsonObj.events[i].title + ", " + jsonObj.events[i].date + ", " + jsonObj.events[i].explanation + "<br/>";
        }
        output.append(val);
    });
});

Side point:

I don't know if it was on purpose or not, but in your OP the JSON file does not look legal, you are missing commas. (source)

share|improve this answer
 
For what its worth (I may have told you this already, but I don't remember), I fixed the lack of the commas between the objects in my json file (a total of 2 missing commas, if I have that right) and your solution does not work. Again, my path and ids have been double, even triple, checked, and everything is as it should be there. I have tried putting your code in a document.ready jQuery function, outside of said function, and even in a jQuery(function ($) function (just to see), still to no avail. No script errors show. This is why I haven't accepted your answer. –  VoidKing Jan 3 at 16:17
 
Just for information's sake, the problem with your code is that you are overrunning the array. The for loop condition should be 'i < jsonObj.events.length' I'm not knocking you, I didn't see it either, and had to be told, myself. Unfortunately at the time of this posting, this error was underneath two others, anyway (my lack of commas and getting IIS express to serve up json files), so they had to be resolved first. Don't know, maybe this will help any future readers. Other than overrunning the array, this code (provided the other errors are taken care of) works fine. –  VoidKing Jan 4 at 14:21
add comment

Your problem is here:

var testjson = $.getJSON('/TestJSON');
jsonObj = JSON.parse(testjson);

$.getJSON already parses the JSON into a JavaScript object, and passes it to your callback.

Use this instead:

$.getJSON('/TestJSON', function (jsonObj) {
    $("#testJSONBtn").click(function () {
        $.each(jsonObj.events, function (){
             $("#JSONOutput").append(this.title + ", " + this.date + ", " + this.explanation + "<br/>");
        });
    });
});

P.S. for performance, consider caching your selector, and appending it all in one fell swoop.

share|improve this answer
 
None-constructive comment: Reading your P.S made me question "one fell swoop" or is it "one fowl swoop", so I looked it up. Interesting stuff to say the least. And now the OP might learn two things today. :) –  rlemon Jan 2 at 20:59
 
Or nothing at all... –  VoidKing Jan 2 at 21:00
 
@Joseph Silber Thanks for trying to help, I appreciate it, but I looked that over, tried it, and not only did it not work, it didn't show any script errors. No external JSON for me. Maybe someone else will ask the question to the satisfaction of the other viewers here and hopefully cause less trolling. Till then I will be voting to close this post (and not asking again, lolz), as it appears to be constructive to absolutely no one (least of all future viewers). –  VoidKing Jan 2 at 21:07
add comment

The title of your question states that you wish to "Get an array of objects from an external json file and store as an array in javascript", so my proposed solution involves storing the data in an array.

var i;
// Prepare an empty array to store the results
var array = [];
// $.getJSON() is a wrapper for $.ajax(), and it returns a deffered jQuery object
var deferred = $.getJSON('/TestJSON');

deferred.done(function (response) {
    // Any code placed here will be executed if the $.getJSON() method
    // was completed successfully.
    for ( i = 0 ; i < response.length ; i++ ) {
        array.push({ 
            title: response.title, 
            date: response.date,
            explanation: response.explanation
        });
    }
});

You can find out more about the returned value of the $.getJSON() function, and also about using the deferred object.

share|improve this answer
 
This is turning into an Abbott & Costello routine. Whacking comments. Please, folks, keep comments on answers relevant to the answer in some fashion. –  Shog9 Jan 2 at 21:57
 
@Shog9 Third base! –  Neal Jan 2 at 22:00
 
Will do @Shog9 man. –  rlemon Jan 2 at 22:00
add comment

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