1

There is a new keyword 'class' in ES6 (ECMAScript 6), and my class is this way:

class MyClass {
    constructor() {
        this.MyProperty = 0;
    }
}

var obj = new MyClass();
console.log(obj);
//result:
//MyClass {MyProperty:0}

var str = JSON.stringify(obj);
console.log(str);
//result:
//"{MyProperty:0}"

The matter is 'str' obtained by using JSON.stringify doesn't contain a class name and thus JSON.parse (or other utils) won't be able to unserialise back to the 'obj' object. After using JSON.parse on 'str', the result is no longer instance of MyClass class.

var objFromStr = JSON.parse(str);
console.log(objFromStr);
//result:
//{MyProperty:0}

How to serialise an instance to string and unserialise back to instance in ES6? If JSON.stringify/JSON.parse don't work, any good libraries for using in NodeJS?

Dee
  • 7,455
  • 6
  • 36
  • 70
  • 1
    JSON doesn't involve the concept of classes. It represents plain objects, arrays, and primitives. If you want to reconstitute your objects to class instances, you can provide a custom function (a "reviver") as the second parameter to `JSON.parse()` to handle the data being parsed and return it in the way you would like. – JLRishe Feb 13 '17 at 10:28
  • 1
    https://www.npmjs.com/package/json-serialize – JLRishe Feb 13 '17 at 11:00
  • 3
    You could have a static method on the class, e.g. `MyClass.fromJSON()`, and implement deserialisation yourself. – sdgluck Feb 13 '17 at 13:37
  • JSON syntax should be amended to include a class name before object for the deserialisation process – Dee May 11 '17 at 23:33

1 Answers1

0

There is no way to deserialise a JSON to object currently as the JSON syntax has no definition about class name. Thus, an unpacker function should come along.

JSON syntax should be amended to include class name before object for the deserialisation process can be done automatically.

Eg.

SomeClass {
    "field1": "value1",
    "field2": "value2"
}
Dee
  • 7,455
  • 6
  • 36
  • 70