Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing JSON using jquery

Tags:

json

jquery

I'm trying to parse a simple JSON file. I'm very new to javascript, JSON, and jquery. I'd like to extract the information in the JSON file so that I can plot it later using protovis. My JSON is well formed, and validates in the JSON lint.

I'm trying to accomplish this by parsing the JSON object's responseText, like this:

var json = $.getJSON("week_13.json").responseText;
var week13 = $.parseJSON(json);

in the hope that week13 is something I can access. Just to note, I'm not trying to use a callback function in the $.getJSON call as I'd like to simply have access to the variables so that I can plot them later.

I'm using Chrome, and its console, to try and figure out what's going on. In this code the variable json seems to be an empty string. However, if I write in the javascript console in Chrome:

var json = $.getJSON("week_13.json");

json is an XMLHttpRequest object and its responseText attribute is a big string containing my JSON.

var text = json.responseText;

is a nice string and then if I call jquery's parser

var data = $.parseJSON(text);

then data is now the object I desired. However, if I copy and paste my original two lines into the console I have no luck, and if I use the expanded version froming the json, text and data variables in my original webpage it doesn't work:

var json = $.getJSON("week_13.json");
var text = json.responseText;
var data = $.parseJSON(json);

In this case text is an empty string.

I'm totally confused. If anyone could let me know what I'm doing wrong and give some pointers as to how to make this work, I'd be very happy! Please let me know if any other information as to how I'm going about this is required to answer the question!

like image 349
Mike Dewar Avatar asked Feb 26 '23 13:02

Mike Dewar


1 Answers

$.getJSON() is asynchronous. You need to supply a callback function to process the result. See the API doc for examples of callback functions.

If you really need your call to be synchronous (it will block the browser while you wait for the result), then you can do this instead:

var url = "week_13.json"
var data = jQuery.parseJSON(
        jQuery.ajax({
            url: url, 
            async: false,
            dataType: 'json'
        }).responseText
    );
like image 97
Kim Burgaard Avatar answered Mar 07 '23 17:03

Kim Burgaard