Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember model to json

Tags:

I am looking for an efficient way to translate my Ember object to a json string, to use it in a websocket message below

/*  * Model  */  App.node = Ember.Object.extend({   name: 'theName',   type: 'theType',   value: 'theValue', }) 

The websocket method:

App.io.emit('node', {node: hash});  

hash should be the json representation of the node. {name: thename, type: theType, ..} There must be a fast onliner to do this.. I dont want to do it manualy since i have many attributes and they are likely to change..

like image 753
Stephan Avatar asked Dec 29 '11 14:12

Stephan


People also ask

What is an ember model?

In Ember Data, models are objects that represent the underlying data that your application presents to the user. Note that Ember Data models are a different concept than the model method on Routes, although they share the same name.

What is serializer in Ember JS?

In Ember Data, serializers format the data sent to and received from the backend store. By default, Ember Data serializes data using the JSON:API format. If your backend uses a different format, Ember Data allows you to customize the serializer or use a different serializer entirely.

What is the default serializer shipped with Ember?

Ember Data ships with 3 Serializers. The JSONAPISerializer is the default serializer and works with JSON API backends.


2 Answers

As stated you can take inspiration from the ember-runtime/lib/core.js#inspect function to get the keys of an object, see http://jsfiddle.net/pangratz666/UUusD/

App.Jsonable = Ember.Mixin.create({     getJson: function() {         var v, ret = [];         for (var key in this) {             if (this.hasOwnProperty(key)) {                 v = this[key];                 if (v === 'toString') {                     continue;                 } // ignore useless items                 if (Ember.typeOf(v) === 'function') {                     continue;                 }                 ret.push(key);             }         }         return this.getProperties.apply(this, ret);     } }); 

Note, since commit 1124005 - which is available in ember-latest.js and in the next release - you can pass the ret array directly to getProperties, so the return statement of the getJson function looks like this:

return this.getProperties(ret); 
like image 141
pangratz Avatar answered Nov 27 '22 17:11

pangratz


You can get a plain JS object (or hash) from an Ember.Object instance by calling getProperties() with a list of keys.

If you want it as a string, you can use JSON.stringify().

For example:

var obj  = Ember.Object.create({firstName: 'Erik', lastName: 'Bryn', login: 'ebryn'}),     hash = obj.getProperties('firstName', 'lastName'), // => {firstName: 'Erik', lastName: 'Bryn'}     stringHash = JSON.stringify(hash); // => '{"firstName": "Erik", "lastName": "Bryn"}' 
like image 39
ebryn Avatar answered Nov 27 '22 17:11

ebryn