16

I'm attempting to load JSON (from php's json_encode) into a Backbone JS collection. I've simplified the problem to:

var myJSON = '[{ "id":"1","name":"some name","description":"hmmm"}]';

var myCollection = new MyCollection(myJSON, { view: this });

And:

MyObject = Backbone.Model.extend({

  id: null,
  name: null,
  description: null
});

MyCollection = Backbone.Collection.extend({ 
model: MyObject,
initialize: function (models,options) { }
});

Error:

Uncaught TypeError: Cannot use 'in' operator to search for 'id' in

Similar Issue: Backbone: fetch collection from server

My JSON certainly appears to be in the right format, am I missing something obvious? I have attempted using simply id: "1" as opposed to "id" with the same result.

Community
  • 1
  • 1
pws5068
  • 2,224
  • 4
  • 35
  • 49

3 Answers3

13

Your JSON is still in string format. Pass it to JSON.parse before assigning it:

var myJSON = JSON.parse('[{"id":1,"name":"some name","description":"hmmm"}]');
kinakuta
  • 9,029
  • 1
  • 39
  • 48
  • 1
    Yep, and if the data is retrieved using something like jquery's $.getJSON method, it will call JSON.parse on it automatically. –  Jan 16 '12 at 06:39
  • 1
    The documentation does show pass json directly to the initialization in at least one example: http://documentcloud.github.com/backbone/#Collection-toJSON (even though the purpose of this demo is how to export json) – pws5068 Jan 16 '12 at 08:35
  • 1
    Notice that they don't mention that the array they pass to the collection constructor has already been parsed. The documentation could probably stand a little clarification there, but the thing to remember is that JSON is typically passed between server and client in string format and needs to either be parsed after receiving or stringified before sending. – kinakuta Jan 16 '12 at 08:54
3

You forgot the defaults hash in your model.

MyObject = Backbone.Model.extend({
  defaults: {
    id: null,
    name: null,
    description: null
  }
});

See the documentation

Paul
  • 18,349
  • 7
  • 49
  • 56
  • Ah, I was so focused on verifying the JSON structure I missed this simple exclusion. Thank you for your help – pws5068 Jan 16 '12 at 06:28
  • @kinakuta yep, the defaults hash is optional, but the model in the example was trying to use the defaults functionality without the hash. – Paul Jan 16 '12 at 15:08
0

so i maybe missing the point completely but the problems seems to be the 'single quotes' around the array. That is, this:

var myJSON = '[{ "id":"1","name":"some name","description":"hmmm"}]';

should be:

var myJSON = [{ "id":"1","name":"some name","description":"hmmm"}];

Php, afik, doesn't add the single quotes, so it should be as simple as changing a line that says:

$my_js = "var myJSON = '" . json_encode($my_array_to_send)) . "';";

to:

$my_js = "var myJSON = " . json_encode($my_array_to_send)) . ";  ";
ErichBSchulz
  • 15,047
  • 5
  • 57
  • 61