Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing an ES6 class object as JSON

class MyClass {
  constructor() {
    this.foo = 3
  }
}

var myClass = new MyClass()

I'd like to serialize myClass object to json.

One easy way I can think of is, since every member is actually javascript object (array, etc..) I guess I can maintain a variable to hold the member variables.

this.prop.foo = this.foo and so on.

I expected to find a toJSON/fromJSON library for class objects since I used them with other languages such as swift/java, but couldn't find one for javascript.

Maybe class construct is too new, or what I'm asking can be somehow easily achieved without a library.

like image 420
eugene Avatar asked Oct 23 '16 09:10

eugene


People also ask

What is serializing in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

Can JSON serialize functions?

Then you can simply use JSON. stringify and functions will be serialized as strings. Its generally a not good idea in most cases. There are very few circumstances where you want to do this and even then, there is probably a better way.

How do you Stringify a class?

Using .stringify() function on an object, it looks for a toJSON() function on that object and, if such a function exists, stringifies the result of that function's return value. This is super handy, since it allows you to add a toJSON() method to your class and output a plain object for stringifying.

Is converting to JSON serialization?

Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into .


2 Answers

As with any other object you want to stringify in JS, you can use JSON.stringify:

JSON.stringify(yourObject); 

class MyClass {    constructor() {      this.foo = 3    }  }    var myClass = new MyClass()    console.log(JSON.stringify(myClass));

Also worth noting is that you can customize how stringify serializes your object by giving it a toJSON method. The value used to represent your object in the resulting JSON string will be the result of calling the toJSON method on that object.

like image 137
nbrooks Avatar answered Sep 21 '22 14:09

nbrooks


I know this question is old but I've been clawing my eyes out until I wrote a compact real, "safe", solution.

Deserialization returns objects that still have working methods attached to them.

The only thing you need to do is register the classes you want to use in the constructor of the serializer.


class Serializer{
    constructor(types){this.types = types;}
    serialize(object) {
        let idx = this.types.findIndex((e)=> {return e.name == object.constructor.name});
        if (idx == -1) throw "type  '" + object.constructor.name + "' not initialized";
        return JSON.stringify([idx, Object.entries(object)]);
    }
    deserialize(jstring) {
        let array = JSON.parse(jstring);
        let object = new this.types[array[0]]();
        array[1].map(e=>{object[e[0]] = e[1];});
        return object;
    }
}

class MyClass {
    constructor(foo) {this.foo = foo;}
    getFoo(){return this.foo;}
}

var serializer = new Serializer([MyClass]);

console.log(serializer.serialize(new MyClass(42)));
//[0,[["foo",42]]]

console.log(serializer.deserialize('[0,[["foo",42]]]').getFoo());
//42

The above should be enough to get you going, but more details and minified version can be found here.

like image 24
guest Avatar answered Sep 17 '22 14:09

guest