javascriptember.js

Ember model to json


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..


Solution

  • Ember Data Model's object counts with a toJSON method which optionally receives an plain object with includeId property used to convert an Ember Data Model into a JSON with the properties of the model.

    https://api.emberjs.com/ember-data/2.10/classes/DS.Model/methods/toJSON?anchor=toJSON

    You can use it as follows:

    const objects = models.map((model) => model.toJSON({ includeId: true }));
    

    Hope it helps. Enjoy!