tags:

views:

54

answers:

2

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.

+1  A: 

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.

Nick Craver
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. . .
Ed
ah, I was passing the wrong json string. d'oh!
Ed
A: 
zod
The question is tagged jQuery/JSON, so this is JavaScript...not sure why you'd send it back to the server as a solution?
Nick Craver
this is a bad answer! there is no need to go do all its completely wasteful. just because you can do something doesn't mean you should.
mcgrailm
There is absolutely no reason to go out to php for this.
Squeegy