14

I have hardcoded classes to represent models in my Aurelia application. Here's a model 'PostEdit':

var _postID = Symbol();
var _title = Symbol();
var _text = Symbol();

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; }

}

After the object is manipulated, I need to PUT and POST it back to the server. But it looks like Aurelia's HttpClient is sending an empty JSON string ({}). Looking into it, it seems that Symbols are ignored when converting an ES6 class to JSON.

How can I go about getting all my properties into a JSON string to submit back to the server?

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • What are you expecting them to look like in the JSON representation? JSON object properties look like `"name": "value"`, but what name shoud be used for a `Symbol`? – Barmar Oct 28 '15 at 04:35
  • See www.json.org for the types of values that can be represented in JSON. You probably need to provide a `toJSON` method in your class to return the desired representation. – Barmar Oct 28 '15 at 04:37
  • @Barmar in the end I need `{ "postID": "1" ...}`. I guess I was hoping for some built-in way to do this – Jonesopolis Oct 28 '15 at 04:38
  • Symbols are a purely JS construct. Properties defined with symbols cannot be serialized. What is your intent in using symbols here? –  Oct 28 '15 at 04:42
  • How would it get the string `postID` from a `Symbol`? You never put that string anywhere in the symbol. – Barmar Oct 28 '15 at 04:42
  • I thought it might work if you used `_postID = Symbol("postID")`, but it still leaves those properties out of the JSON. JSON can only handle properties whose keys are strings or integers. – Barmar Oct 28 '15 at 04:45
  • I had thought I needed symbols to set up my getters and setters. Can I just use a private backing field that can be serialized? – Jonesopolis Oct 28 '15 at 04:47
  • [The documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) is clear about this: **Symbol-keyed properties will be completely ignored when using JSON.stringify()** – Barmar Oct 28 '15 at 04:47
  • 1
    Why do you need getters and setters? They're not doing anything other than you would get if you used ordinary properties. – Barmar Oct 28 '15 at 04:49
  • I'm from a c# background, and like the idea of setting access levels on props. I guess it could be overkill? – Jonesopolis Oct 28 '15 at 04:52
  • 1
    @Jonesopolis: Definitely overkill. You may use them if you add validation or parsing or whatever in the getter/setter body, but if you just assign/access a "more private" property it hardly is useful. Btw, symbols are not private, they are just hidden from being enumerated in normal loops or things like `JSON.stringify`. They still can be accessed by anybody who wants to. – Bergi Oct 28 '15 at 08:52

6 Answers6

29

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

Mulan
  • 129,518
  • 31
  • 228
  • 259
17

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(){
  // ...
}
Fareed Alnamrouti
  • 30,771
  • 4
  • 85
  • 76
7

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
3

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.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
0

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.

Martijn Mellens
  • 520
  • 7
  • 25
0

How can I go about getting all my (symbol) properties into a JSON string to submit back to the server?

To get all symbol properties, you can use Object.getOwnPropertySymbols() to get an array of all symbol properties found directly upon a given object. Such as:

const pe = new PostEdit({...});
const symbols = Object.getOwnPropertySymbols(pe);

However, as all three symbol properties of PostEdit are using empty description (new Symbol(), without any description parameter), there is no way to distinguish these 3 symbols. If the above symbols array is printed, you will get:

//console.log(symbols)
[ Symbol(), Symbol(), Symbol() ]

So, if you want to serialize/deserialize PostEdit instance without adding toJSON()/fromJSON() method to PostEdit class, you can provide meaningful description for symbols and then serialize them accordingly:

var _postID = Symbol('postID');
var _title = Symbol('title');
var _text = Symbol('text');

export class PostEdit {
  ...
}

const pe = new PostEdit({...});
const symbols = Object.getOwnPropertySymbols(pe);
const serializeObj = {};
for (let s of symbols) {
  serializeObj[s.description] = pe[s];
}
const serializedText = JSON.stringify(serializeObj);

To make above serialize/deserialize steps more convenient to use, and also fix the identical-symbol-description issue, I've made an npm module named esserializer and implemented these logic in its pro version.

shaochuancs
  • 15,342
  • 3
  • 54
  • 62