Jonesopolis Jonesopolis - 1 year ago 155
JSON Question

Convert ES6 Class with Symbols to JSON

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
it back to the server. But it looks like
is sending an empty
string (
). Looking into it, it seems that
are ignored when converting an ES6 class to

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

Answer Source

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


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