0

Hi I have a json array being returned from the server.. it looks something like this:

[{ ImageUrl="http://www.google.com"}, { ImageUrl="http://www.bing.com"}]

I have this:

<div id="images"></div>

and Im trying to create images based on the data, but I'm struggling with the jquery

$.each(json.imageData.ImageUrl, function (i, ImageUrl) {
  $("<img/>").attr("src", ImageUrl).appendTo("#images");

});

How can i make it add images to the div?

1
  • Is that the actual JSON? It's invalid... Commented Jan 7, 2011 at 12:05

1 Answer 1

4

Firstly, your JSON is invalid. You can validate it here: http://jsonlint.com

I think what you are trying to do, is this:

[
    {
        "ImageUrl": "http://domain.com/image.jpg"
    },
    {
        "ImageUrl": "http://domain.com/image2.jpg"
    }
]

Notice the double quotes that were missing in your code. In JSON you are required to use double quotes (never single or without quotes) on both the key and value.

Secondly, you are trying to iterate the value and not the array.

Try with this:

$.each(json.imageData, function (i, img) {
    $("<img>").attr("src", img.ImageUrl).appendTo("#images");
});
Sign up to request clarification or add additional context in comments.

3 Comments

what if each item had more values? e.g {"ImageUrl":"domain.com/image.jpg", "Alt":"FooBar" }
Sorry, my mistake. As you can see in the updated example you can access the object with img.ImageUrl, so if you want to access Alt, just do it with img.Alt. Hope that helps!
I checked the JSON site (json.org) and it defines string as enclosed in double quote. Gee, I thought single quote is enough. I suspect that double quote is used for the sake of consitency in the JSON format.

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.