Backbone: Create collection from JSON

28,976

Solution 1

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"}]');

Solution 2

You forgot the defaults hash in your model.

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

See the documentation

Share:
28,976
pws5068
Author by

pws5068

Developer for a mobile Tech Startup in San Francisco

Updated on July 09, 2022

Comments

  • pws5068
    pws5068 almost 2 years

    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.

  • pws5068
    pws5068 over 12 years
    Ah, I was so focused on verifying the JSON structure I missed this simple exclusion. Thank you for your help
  • Admin
    Admin over 12 years
    Yep, and if the data is retrieved using something like jquery's $.getJSON method, it will call JSON.parse on it automatically.
  • pws5068
    pws5068 over 12 years
    The documentation does show pass json directly to the initialization in at least one example: documentcloud.github.com/backbone/#Collection-toJSON (even though the purpose of this demo is how to export json)
  • kinakuta
    kinakuta over 12 years
    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.
  • Paul
    Paul over 12 years
    @kinakuta yep, the defaults hash is optional, but the model in the example was trying to use the defaults functionality without the hash.