I\'m buiding my first app in backbone and I want to know which is the best mode to parse a json with multiple level. This is a simple small example of json:
First of all, that JSON structure is really, truly bizarre. Fix your server or ask your server team to seek therapy. But assuming you can't un-ridiculousify the server's JSON, here's how to make it into a backbone-compatible array:
var HotelsCollection = Backbone.Collection.extend({
model: Hotel,
url: "includes/test-data.json",
parse: function(response){
//remove prefix/wrapper object and collect "hotel" 1-element arrays
var sillyArrays = _.pluck(response.hotels, 'hotel');
//Extract the hotel objects from their silly 1-element arrays
//Synthesize a fake id attribute since backbone expects that
var hotels = _.map(sillyArrays, function (hotelArray, index) {
return {name: hotelArray[0].name, id: index + 1};
});
return hotels;
}
});
That parse
function will return this data, which backbone will understand.
[ { name: 'Hotel1', id: 1 },
{ name: 'Hotel2', id: 2 },
{ name: 'Hotel3', id: 3 } ]
Also note the lack of an id
attribute is another thing you'll need to eventually resolve in order for your application to work properly with backbone.