larryq
larryq

Reputation: 16309

Converting this string to JSON object array using jQuery

I have a web service that returns this string via the jQuery $.ajax() call in the success callback:

[{"WaitlistID":1,"RID":45034,"CustomerID":2765957,
 "IsAdmin":false,"TruckSize":1,"Points":1},
 {"WaitlistID":2,"RID":45034,"CustomerID":2765957,
 "IsAdmin":false,"TruckSize":1,"Points":1}]

Unfortunately if I call $.each() on that value in the success callback it iterates over every letter in it, and doesn't treat it as a two element array, which is what I'd like. I've tried the makeArray() function but haven't had any luck, how can I convert that string into a JSON object array?

edit:

In response to the comments (thanks, everyone) I already do set the dataType to 'json', which is odd. Here's the code in question.

jQuery.ajax({
    type: "POST",
    url: pagePath + "/" + fn,
    contentType: "application/json; charset=utf-8",
    data: paramList,
    dataType: "json",
    success: successFn,
    error: errorFn
});

..so I'm not sure why it didn't work originally, but the parseJSON() bit did the trick. Appreciate everyone's help.

Upvotes: 2

Views: 10931

Answers (4)

Jonathan M
Jonathan M

Reputation: 17451

You have:

success: successFn

Does successFn() exist, and will it take a parameter? I.e., is it defined like function successFn(myObject)? If so, myObject will contain the object described by the JSON string. No parsing necessary.

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79850

What you have is returned is a string.. Try to set the dataType in $.ajax call.

$.ajax({
   url: blahblah,
   dataType: 'json',
   ...
});

Upvotes: 1

Pethical
Pethical

Reputation: 1482

Try to parse with jQuery.parseJSON()!

Upvotes: 1

alexn
alexn

Reputation: 59012

You can use jQuery.parseJSON to parse it:

var obj = $.parseJSON(str);

However, jQuery should already do this for you if the server returns the correct content-type. If it is not, you can specify jQuery to treat the response as JSON:

$.get("test.php", function(data){
   // callback
}, "json");

Or even better, use jQuery.getJSON.

Upvotes: 4

Related Questions