jiexi
jiexi

Reputation: 3029

$.getJSON and $.each

So i'm trying to cycle through a JSON response, but I can't seem to get it right.

Snippet:

$.getJSON("/playlist/",function(playlists) {
    $.each(playlists,function() {
        self.playlists[this.playlist.id] = new SC.Playlist(this, self);
        console.log(this);
    })
})

JSON:

jsonp1311444173992([
  {
    is_owner: true,
    id: "wtf",
    playlist: {
      id: "latest1",
      name: "Hot Tracks1",
      version: 0,
      tracks: "33+44+55"
    }
  },
  {
    is_owner: true,
    playlist: {
      id: "latest",
      name: "Hot Tracks",
      smart: true,
      version: 0,
      smart_filter: {
        order: "hotness"
      }
    }
  },
  {
    is_owner: true,
    playlist: {
      id: "latest3",
      name: "Hot Tracks3",
      version: 0,
      tracks: "33+44+55"
    }
  },
  {
    is_owner: true,
    playlist: {
      id: "latest4",
      name: "Hot Tracks4",
      version: 0,
      tracks: "33+44+55"
    }
  },
  {
    is_owner: true,
    playlist: {
      id: "latest5",
      name: "Hot Tracks5",
      version: 0,
      tracks: "33+44+55"
    }
  }
]);

It just doesn't seem to go down the JSON list. Did I not call one of the variables correctly?

Upvotes: 0

Views: 446

Answers (2)

Christian
Christian

Reputation: 28165

First of, the JSON you're showing us....isn't exactly JSON. I'm not sure if jQuery.getJSON can read that.

Secondly, I don't know what self does. I think it refers to the outermost scope, right?

Thirdly, is it too much to ask for properly indented and runnable code?:

$.getJSON("/playlist/",function(playlists) {
    $.each(playlists,function() {
        self.playlists[this.playlist.id] = new SC.Playlist(this, self);
        console.log(this);
    }
}

By the way, I'd do console.log(playlists,self,this) to ensure everything is ok.

Upvotes: 0

SeanCannon
SeanCannon

Reputation: 78006

This is invalid JSON. You need to quote your keys:

{
    "is_owner": true,
    "id": "wtf",
    "playlist": {
      "id": "latest1",
      "name": "Hot Tracks1",
      "version": 0,
      "tracks": "33+44+55"
    }
  },

.. and so on.

A handy reference for future projects is the JSONLint JSON Validator

Upvotes: 5

Related Questions