spine/spine — pull request #542 by richard-flosi (2014-05-21 16:14:51+00:00)
Title: Adding Model.beforeFromJSON() hook to tap into the json before the default fromJSON() method runs.

Adding a light `Model.beforeFromJSON()` hook to allow developers to transform their json before the normal `Model.fromJSON()` method runs. The default implementation simply returns the original `objects` data that was passed to it. i.e. a noop.

In my experience `fromJSON()` pretty much does what you want, but when working with custom APIs or HATEOAS APIs like [Tastypie](https://django-tastypie.readthedocs.org/en/latest/interacting.html#getting-a-collection-of-resources) you often need to pick off some root data attribute from the response in `fromJSON()` which leads to a lot of duplicate code. This Pull Request gives you the opportunity to make that small tweak and then let `fromJSON()` do its work.

For APIs that are designed with older browsers and the [JSON Array Information Disclosure Vulnerability](http://stackoverflow.com/questions/16289894/is-json-hijacking-still-an-issue-in-modern-browsers) in mind this Pull Request also helps address collections that are wrapped in an object in the same way.

For APIs where the root object attribute is always known you could do something like this:

```
Spine.Model.root = 'data';
Spine.Model.beforeFromJSON = function(objects) {
if (typeof objects === 'object' && this.root && objects.hasOwnProperty(this.root)) {
return objects[this.root];
} else {
return objects;
}
};
```

The example above checks sets a globally known root object attribute `data` and then checks if `objects` is an `object` with the `data` attribute and if so, returns just the `data` attribute.

In my case we have an API that always returns a response like: `{meta: {}, data: [], errors: []}` or `{meta: {}, data: {}, errors: []}` and I use a setup like the example above so my models can use the default `fromJSON()` method.