Reputation: 4474
I have a probably quite simple to solve problem. I'm trying to parse this JSON file using jquery:
My jQuery code looks like that:
$.post("/xhr/fav_switch", {event_id: event_id}, function(data) {
event = jQuery.parseJSON(data);
alert(event.pk);
});
but no matter which field i'm trying to access in alert, it allways says undefined
. have you any idea what am i doing wrong? Any help would be appreciated :)
Upvotes: 0
Views: 443
Reputation: 150010
First of all your data is an array with exactly one element, so you need to access it as:
event[0].pk
event[0].fields.updated
// etc
But also jQuery ajax methods usually parses the JSON for you so you may find you can just say:
data[0].pk
data[0].fields.updated
without needing to use event = jQuery.parseJSON(data)
.
Upvotes: 1
Reputation: 45721
$.post("/xhr/fav_switch", {event_id: event_id}, function(data) {
var events = jQuery.parseJSON(data);
var event = events[0];
alert(event.pk);
});
You get an array (with one element) back, so event is an array. You need to get the first element of the array to get to the event object itself.
Upvotes: 3