0

I'm trying to parse the following json line in jquery:

[{
   "pk": 19,
   "model": "films.movies",
   "fields": {
       "length": "92",
       "name": "Beetle Juice",
       "actor": "Keaton", 
       "img_set": [{
             "pk": 42,
             "model": "films.img",
             "fields": {
                 "uploaded": "2010-10-08 21:44:30",
                 "f_movie": 19,
                 "url_med": "http://www.mondial-infos.fr/wp-content/uploads/2009/10/Beetlejuice.jpg"}
             }]
       }
},{
   "pk": 20,
   "model": "films.movies",
   "fields": {
      "length": "126",
      "name": "Batman",
      "actor": "Keaton", 
      "img_set": [{
            "pk": 43, 
            "model": "films.img",
            "fields": {
                  "uploaded": "2010-10-08 21:44:54",
                  "f_movie": 20, 
                  "url_med": "http://bruehoyt.com/superheroes/DC/batman/bruce/batmankeaton3.jpg"}
            }]
      }
}]

I can't access anything after img_set though. What am I missing? Is this valid json?

I am attempting the following:

$.getJSON('/films/feeds/movie-by-actor/Keaton/',function(data) {
    $.each(data, function(i, movie) {

        alert(movie.fields.name);
        alert(movie.fields.img_set[0].pk);

    });
});

The first alert works. The second does not.

In addition, though I don't know that it matters, this is jquery within a django template.

5
  • are you getting an error? how you are accessing? Commented Oct 9, 2010 at 18:26
  • It's valid JSON. Do you mean you can't access any of the properties in the objects in the img_set array, or you can't access the second element in the main array? Code that demonstrates the problem you're having would help. Commented Oct 9, 2010 at 18:27
  • edited above with code I'm using to try to access data Commented Oct 9, 2010 at 18:37
  • you need alert(movie[0].fields.img_set[0].pk); because move is an array look at Nick's code see how he has it in his Commented Oct 9, 2010 at 19:00
  • Figured it out. Thanks, all! Commented Oct 9, 2010 at 20:37

1 Answer 1

1

The confusing part is probably the array of a single element, but img_set is still an array. Make sure you're accessing it with an index first, like this:

.img_set[0].pk
//for example:
data[0].fields.img_set[0].pk

Instead of just:

.img_set.pk

You can give it a try here.

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

1 Comment

First, thanks for the link. That's a handy tool. It's weird though that it works there, but it's not working in my code. Same methodology. . .

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.