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.
asked Oct 9, 2010 at 18:25
Ed.
4,59711 gold badges62 silver badges81 bronze badges
1 Answer 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
answered Oct 9, 2010 at 18:26
Nick Craver
631k138 gold badges1.3k silver badges1.2k bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Ed.
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. . .
lang-js
img_setarray, or you can't access the second element in the main array? Code that demonstrates the problem you're having would help.