Search code examples
javascriptjsonember.jsember-dataember-cli

Ember - how to clean up JSON response


I'm pretty new to EmberJS and unfortunately I have to deal with JSON that doesn't include a root or ids and I can't seem to find any clear way to accomplish what I'm trying to do, which is just to clean up the response.

I assume that I need to be using an ember serializer to do this.

This is what I currently get from my api/locations:

[
  {
    "uri": "/location/1",
    "name": "ATLANTA"
  },
  {
    "uri": "/location/2",
    "name": "NORTH VIRGINIA"
  }
]

I assume that I need it to look like this instead, with a root and id's:

{
   "locations":[
     {
        "id":"1",
        "uri":"/location/1",
        "name":"ATLANTA"
     },
     {
        "id":"2",
        "uri":"/location/2",
        "name":"NORTH VIRGINIA"
     }
    ]
 }

I added a JSONSerializer under app/serializers/location.js

import DS from 'ember-data';

export default DS.JSONSerializer.extend({
    // how can I manufacture an id here, say with index
    // how to I assign it to a root called "locations"
});

Just by including this JSONSerializer I do get a record in the store but it's only one and I assume that's because they don't have ids otherwise both entries would show up.

only one record and no id

I need help and examples of how to begin massaging this data. The examples I have tried didn't do anything.


Solution

  • It appears that JSONSerializer fixes the root issue I mentioned but I was able to resolve my id issue by experimenting with the available methods on the serializer until I landed on something that worked. My final solution looks like this:

     export default DS.JSONSerializer.extend({
    
        normalize: function(typeClass, hash) {
           hash['id'] = parseFloat(hash.uri.match(/\d+/g))
           return this._super.apply(this, arguments);
        }
    
     });
    

    Simple enough but, WOW, I couldn't find a single example that showed how to do something like this.