Ember model to json

后端 未结 12 1382
北恋
北恋 2020-12-13 13:55

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


        
12条回答
  •  孤街浪徒
    2020-12-13 14:42

    I have also been struggling with this. As Mirko says, if you pass the ember object to JSON.stringify you will get circular reference error. However if you store the object inside one property and use stringify on that object, it works, even nested subproperties.

    var node = Ember.Object.create({
      data: {
        name: 'theName',
        type: 'theType',
        value: 'theValue'
      }
    });
    
    console.log(JSON.stringify(node.get('data')));
    

    However, this only works in Chrome, Safari and Firefox. In IE8 I get a stack overflow so this isn't a viable solution.

    I have resorted to creating JSON schemas over my object models and written a recursive function to iterate over the objects using the properties in the schemas and then construct pure Javascript objects which I can then stringify and send to my server. I also use the schemas for validation so this solution works pretty well for me but if you have very large and dynamic data models this isn't possible. I'm also interested in simpler ways to accomplish this.

提交回复
热议问题