views:

45

answers:

3

I am returning a JSON object (as a String) through a servlet. The JSON object looks like this:

{"3":"Martin Luther","30":"Boris Becker","32":"Joseph Goebels","19":"Leonardo Da Vinci","31":"Adolf Hitler"}

My jQuery looks like this (the submission of data is correct because I get a proper looking result from the servlet):

$.ajax( {
            type : "GET",
            url : "MyServlet",
            data : queryString + "count=" + variables,
            success : function(resultObj) {
              $.each(resultObj, function(key, value) {
                    $("#resultCount").html(key+", "+value); 
                 });
            }
        });

However when I try to print the results, that is the variables key and value, I get a number for the key but not a number from the JSONObject and an empty string instead of the value.

Essentially the question is about how to "extract" the information from a JSON object.

+3  A: 

Your JSON is not an array. It should look like this:

[{ "3":"Martin Luther" },
 { "30":"Boris Becker" }]

or even better:

[{ id: "3", name: "Martin Luther" },
 { id: "30", name: "Boris Becker" }]

Then you can loop:

$.each(data, function(index, item) {
    alert(item.id + ' ' + item.name);
});
Darin Dimitrov
jQuery's `.each` method will do iteration over key/value pairs for objects.
bcherry
+2  A: 

Try specifying dataType as json in your AJAX call:

$.ajax( {
        type : "GET",
        url : "MyServlet",
        data : queryString + "count=" + variables,
        dataType : 'json',
        success : function(resultObj) {
          $.each(resultObj, function(key, value) {
                $("#resultCount").html(key+", "+value); 
             });
        }
    });
Will Vousden
You don't need to do this. The content type is already set by the server as the OP indicated in the comments section and jQuery will automatically deserialize the string to an object.
Darin Dimitrov
"text/json" is _not_ a valid type. The correct type is "application/json". Perhaps jQuery will interpret "text/json" as _meaning_ "application/json", but I doubt it.
bcherry
@bcherry, you are right `application/json` should be used.
Darin Dimitrov
+1  A: 

Couple things:

  1. You should be using the JSON data type. Try the simpler $.getJSON method.
  2. Your iteration is correct, but you'll be overwriting the previous results on each iteration (i.e. it comes out as just the Hitler entry)
bcherry