Convert ES6 Class with Symbols to JSON

对着背影说爱祢 提交于 2019-11-29 04:33:23

I'm assuming you're using symbols to keep the data private, but this means you're going to have to go through some extra steps if you want that data included in the JSON representation.

Here's an example using toJSON on your model to explicitly export the properties you care about

export class PostEdit {

  // ...
  toJSON() {
    return {
      postID: this.postID,
      title:  this.title,
      text:   this.text
    };
  }
}

Or

export class PostEdit {

  // ...
  toJSON() {
    let {postID, title, text} = this;
    return {postID, title, text};
  }
}

When JSON.stringify is called on your instance, it will automatically call toJSON

Give your class a toJSON method that returns a stringifyable object:

export class PostEdit {

    constructor(postEdit) {
        this[_postID] = postEdit.postID;
        this.title = postEdit.title;
        this.text = postEdit.text;
    }

    get postID() { return this[_postID]; }

    get title() { return this[_title]; }
    set title(val) { this[_title] = val; }

    get text() { return this[_text]; }
    set text(val) { this[_text] = val; }

    toJSON() {
        return {
            postId: this.postId,
            title: this.title,
            text: this.text
        };
    }
}

JSON.stringify will automatically call that and replace your instance with the result.

Also you might want to add a fromJSON method to your class that you can use to revive instances during JSON.parse. It is trivial in your case:

    static fromJSON(obj) {
        return new this(obj);
    }

but you might need something more complicated in other classes.

for more dynamic solution use this:

export class MeMe(){
 toJSON() {
    return Object.getOwnPropertyNames(this).reduce((a, b) => {
      a[b] = this[b];
      return a;
    }, {});
  }
}

or you can use my json-decorator :)

import json from "json-decorator";  

@json("postID") // pass the property names that you want to ignore
export class MeMe(){
  // ...
}

Symbol-based private variables are considerable recipe for encapsulation in ES6. The encapsulation in JS is rarely justified, but these are accessors (not symbols) that cause problems here.

Accessors are prototype methods in ES6 classes. So the property is defined not on instance but on prototype, it is non-enumerable. It can be seen in transpiled code, or by checking

postEditInstance.hasOwnProperty('postID') === false
Object.getPrototypeOf(postEditInstance).hasOwnProperty('postID') === true
Object.getPrototypeOf(postEditInstance).propertyIsEnumerable('postID') === false

JSON.stringify, on the other hand, serializes only own enumerable properties of the object.

The solution is to use toJSON method to serialize the object according to the desirable conditions. Or to use Occam's razor on model's accessors, especially if they aren't crucial there.

I wanted to have the whole class assigned to an object using Object.assign

My initial perspective on using this on a class assigning the allocated class to object. This created an infinite loop for _json in chrome. Bad idea.

class test {
    constructor() {
        this._json = {type: 'map'};
        Object.assign(this, this._json);
    }
    toJSON(){
        Object.assign(this._json, this);
        return this._json;
    }
}

I had to exclude the _json variable, so I iterated over the class variables to exclude it.

class test2 {
    constructor() {
        this._json = {type: 'map'};
        Object.assign(this, this._json);
    }
    toJSON(){
        Object.assign(this._json, {
            conv() {
                let ret = {};
                for(let i in this )
                {
                   if(i !== '_json') 
                       ret[i] = this[i];
                }
                return ret;
            }
        } );
        return this._json;
    }
}

but weirdly enough _json gets ignored even without if(i !== '_json')

have not fully tested it, but I thought this would be a good share.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!