2

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.

2
  • 1
    Your ajax call is not properly configured. Use dataType:json. It will parse the json for you and give you an object as the parameter to your success() function. Commented Jun 18, 2012 at 20:25
  • There's is no such thing as a "JSON object". Your string already is JSON. What you want is a JavaScript object. Commented Jun 18, 2012 at 20:42

4 Answers 4

4

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.

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

Comments

1

Try to parse with jQuery.parseJSON()!

3 Comments

Yes, just found that method and was returning here to answer my own question. Thanks!
Better to use dataType:json in your $.ajax() call. You don't have to mess with parseJSON() that way.
@larryq Instead of parseJSON, you should add dataType: 'json' option to $.ajax
1

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

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

1 Comment

I do have the dataType set to json, which made my original problem all the stranger. Thanks for the assist.
1

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.

Comments

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.