Search code examples
jsonparsingbackbone.jscollections

Backbone make a collection from specific Json attribute


I'm having troubles to understand how Backbone collections mapping external json files...If you have a kind of json and you only work to create models from an specific atribute of that json, how did you do that?

            var Comic = Backbone.Model.extend();
            var ComicCollection = Backbone.Collection.extend({
            url: 'http://www.theurlofthejson.com',
            parse: function (response) {
                  return response.comicsbooks;
                  },
            model: Comic,
           });

If then I create a collection

var comicCollection = new ComicsCollection();

if a make this

console.log(comicCollection.fetch())

It returns me the entire json not parsed at the comicsbooks level

Why do I get the entire structure of the json object and not only my comicbooks attribute?

My question is based on this one but the implementation/solution don't work for me Parsing json backbone

Sorry, I miss a sample of the json response of the url attached:

{
    "status": "ok",
    "count": 1,
    "count_total": 4,
    "pages": 4,
    "comicsbooks": [
        {
            "id": 363,
            "type": "american_comics",
            "status": "publish",
            "title": "Popeye"
        }
    ]
}

Solution

  • Your parse method is wrong. It looks like you're overriding your Comic model variable. If you only want the comicbooks property to make up your collection do:

    parse: function(response){
        return response.comicbooks;
    }