Backbone JS parse json attribute to a collection's model

15,002

The parse function should return the attributes hash to be set on the model (see the documentation here). So you'll need simply:

parse: function (response) {
   return response[0].items;
}
Share:
15,002
asirgado
Author by

asirgado

Updated on July 25, 2022

Comments

  • asirgado
    asirgado almost 2 years

    I'm having trouble parsing a json to a model.

    Here is the JSON:

    [
    {
        "name": "Douglas Crockford",
        "email": "[email protected]",
        "_id": "50f5f5d4014e045f000002",
        "__v": 0,
        "items": [
            {
                "cena1": "Cena1",
                "cena2": "Cena2",
                "cena3": Cena3,
                "cena4": "Cena4",
                "cena5": "Cena5",
                "cena6": Cena6,
                "_id": "50ee3e782a3d30fe020001"
            }
        ]
    }
    

    ]

    And i need a model to have the 'items' attributes like this:

    cena = new Model({ 
               cena1: "Cena1", 
               cena2: "Cena2",
               ... 
    });
    

    What I've tried:

    var cenaCollection = new Backbone.Collection.extend({
       model: Cenas,
       url: '/orders',
    
       parse: function (response) {
          return this.model = response.items;
       }
    
    });
    

    then I create new instance of the collection and fetch, but i get "response.items" always "undefined" :|

    Thanks in advance!

  • McGarnagle
    McGarnagle over 11 years
    @asirgado I just noticed your JSON seems to be wrapped in an array -- is that correct? If so you'll need instead response[0].items ...?
  • asirgado
    asirgado over 11 years
    just tried that and it works as I need! Thanks!! If I get more 'items' inside the array will it work? Thanks!