tags:

views:

468

answers:

2

Currently I'm using the helper methods outlined here to return some JSON from my .ashx: http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx

Problem is, I get [ and ] wrapped around my JSON which is malformed...jQuery cannot pick it up in the callback:

[{"ImageTag":"<img src="http://www.xxx.com/image/473.jpg" alt="">"},{"ImageTag":"<img src="http://www.xxx.com/image/485.jpg" alt="">"}]

So I don't know why I get brackets around this. Here is my implementation:

private void GetImagesJSON(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    context.Response.Charset = Encoding.UTF8.ToString();

    int i = 1;

    List<Product> products = GetTestProducts();
    List<CtImageList> imageList = new List<CtImageList>();

    foreach(Product p in products)
    {
        string imageTag = HttpUtility.HtmlEncode(string.Format(@"<img src=""{0}"" alt="""">", ImageUrl(p.Image, false)));

        imageList.Add(new CtImageList{ImageTag = imageTag});
        i++;
    }

    string jsonString = imageList.ToJSON();
    context.Response.Write(jsonString);
}

Here is the callback function in jQuery which can't parse that because of the starting [ and ]:

function itemLoadCallback(carousel, state) {

    // Only load items if they don't already exist
    if (carousel.has(carousel.first, carousel.last)) {
        return;
    }

    $.getJSON("http://localhost:59396/xxx/CHandler.ashx?action=productsjson",
        function(data) {
            $.each(data.items, function(i, item) {
                alert('got here');
                carousel.add(i, mycarousel_decodeEntities(item.ImageTag));
                if (i == 3) return false;
            });
        });
};
A: 

Actually, that should be valid json. The "[" and "]" indicate a list because you called ToJSON on a list of objects. So you have to treat the results as an array. Check out the sample below...

  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
       var a = eval("[1,2,3]");
       for(var i in a) { $("#results").append("<p>" + a[i] + "</p>"); } });
  </script>
  <div id="results"></div>

so for your code the function is:

var images = eval('[{"ImageTag":"&lt;img src=&quot;http://www.xxx.com/image/473.jpg&amp;quot; alt=&quot;&quot;&gt;"},{"ImageTag":"&lt;img src=&quot;http://www.xxx.com/image/485.jpg&amp;quot; alt=&quot;&quot;&gt;"}]');
for(var i in images){
$("#mydiv").append(images[i].ImageTag);
}
Tim Hoolihan
+1  A: 

AFAIK, your response is well-formatted JSON. The brackets are there to tell javascript parses that you are using an array. Passing your JSON to eval() would return you an array with 2 objects.

If your callback is waiting for a single "ImageTag" object, you will get an error.

wtaniguchi
check this out then if you could:http://groups.google.com/group/jquery-en/browse_thread/thread/a3bac00f90d7d8c8if this is valid JSON then why does jQuery seem not to be able to parse it into a data object?
CoffeeAddict
look at my post above, you have to iterate through the array of the items
Tim Hoolihan
And I do that in the jQuery getJSON. The problem is, jQuery can't parse my JSON first in order to shove it into that object "data". It's got a problem with the [ ]. [ ] are fine when inside a key/value pair but not ok to start JSON with I don't think.
CoffeeAddict
jquery automatically passes it to eval(). The problem is I can't even get jQuery do to this because jQuery has a problem with my malformed JSON here. I can then use $.each in jQuery to iterate through the object that jQuery creates when parsing my JSON but again, my JSON is malformed.
CoffeeAddict
use your own eval directly, as in the sample in my post. I used it with your data and it works.
Tim Hoolihan
It's not malformed. It's JSON syntax for an array, which is exactly what you told it to serialize. And that's perfectly valid for the top level. Per the RFC, "A JSON text is a serialized object *or array*" (emphasis mine). http://www.ietf.org/rfc/rfc4627.txt?number=4627
Joe White
the json, is not malformed. that is a valid array.
Tim Hoolihan
Like Tim is saying, your JSON is definitely well-formated.If jQuery can't parse your JSON, I think this a jQuery bug. Using your own parser or even another parser lib would do it.Just because jQuery doesn't parse it automagically doesn't make it wrong. ;D
wtaniguchi