Serializing a javascript class object?

how json stringify works
json stringify depth
json stringify is not a function
json stringify replacer
json.stringify pretty
json stringify error
javascript serialize object for post
json stringify escape quotes

The requirement is simple. Here's a class...

class myobj {

    constructor(var1, var2) {
        this.var1 = var1;
        this.var2 = var2;
    }

    addThemUp() {
        return this.var1 + this.var2;
    }

}

Now I make one of these...

var myInstance = new MyObj(3, 7);

Lovely. But now I need to serialize this so that I can save it and load it up later. Something like...

serialise(myInstance);
// Save to a file
// ... do some other stuff ...
// load from file
myInstance = unserialise(fileData);
// - or - 
unserialise(fileData, myInstace);
// etc...

How? I don't care what form the representation takes as it will be loaded by the same page. If values-only are saved, a generic way of loading them back into an object would be fine because the same page has the class 'template' to find the definitions for the functions.

The object is large and changing, so manually copying the values from JSON in order to preserve the functions wouldn't be practically maintainable. But a solution that could do that with any number and typeof variables would be useful.

I've also got to stick to vanilla, single-file javascript, albeit in modern browsers.

TL;DR: How can I serialise and unserialise an object without losing the functions?

You can use JSON.stringify, but be aware that it only serialize properties, not methods. So to unserialize an object, just create a dummy instance and use Object.assign to update the properties using the retrieved object:

function serialize(instance) {
    var str = JSON.stringify(instance);
    // save str or whatever
}

function unserialize(str, theClass) {
    var instance = new theClass();                  // NOTE: if your constructor checks for unpassed arguments, then just pass dummy ones to prevent throwing an error
    var serializedObject = JSON.parse(str);
    Object.assign(instance, serializedObject);
    return instance;
}

Example:

function serialize(obj) {
    var str = JSON.stringify(obj);
    return str;
}

function unserialize(str, theClass) {
    var instance = new theClass();
    var serializedObject = JSON.parse(str);
    Object.assign(instance, serializedObject);
    return instance;
}

// TEST CLASS

class TestClass {
    constructor(a, b) {
        this.a = a;
        this.b = b;
    }

    sum() {
        return this.a + this.b;
    }
}

// USAGE

var instance = new TestClass(5, 7);

var str = serialize(instance);

var retrievedInstance = unserialize(str, TestClass);

console.log(retrievedInstance.sum());

Serializing an ES6 class object as JSON, Serializing Objects Object serialization is the process of converting an object's state to a string from which it can later be restored. ECMAScript 5 provides native​  Serialize properties of derived classes. Serialization of a polymorphic type hierarchy is not supported. For example, if a property is defined as an interface or an abstract class, only the properties defined on the interface or abstract class are serialized, even if the runtime type has additional properties.

you can use JSON.stringify(myInstance); (to serialize the object) and use JSON.parse(mymyInstance) to get it back as an object

Serializing Objects, A bit of background. I've been working with JSON since 2009 and all I knew is that you are able to serialize JavaScript objects, by using JSON.stringify  Rather than take the approach of serializing and deserializing JavaScript objects to an internal format the approach here is to serialize JavaScript objects out to native JavaScript. This has the advantage that the format is totally agnostic from the serializer, and the object can be recreated simply by calling eval().

There is no way to serialize functions.

Can set up constructor to always take an object and use Object.assign() to assign all the input to instance

Stringify the enumerable properties to json, then when you need it again parse the json and pass that stored object to new MyObj again.

class MyObj {

  constructor(obj) {
    const defaults = {var1: 10,var2: 10};
    Object.assign(this, obj || defaults);
  }

  addThemUp() {
    return this.var1 + this.var2 + (this.var3 || 0) + (this.var4 || 0);
  }

  addSomeProps() {
    if (!this.var3 && !this.var4) {
      this.var3 = 10;
      this.var4 = 10
    }
  }

  serialize() {
    return JSON.stringify(this)
  }

}

const myInstance = new MyObj();
console.log('myInstance before more props added', myInstance)
myInstance.addSomeProps()
///stringify the instance object
const json = myInstance.serialize();
// same variables needed to pass to constructor
const storedObj = JSON.parse(json)
// create new instance
const instance2 = new MyObj(storedObj);

console.log('instance 2', instance2)
// try out the methods 
console.log('add in instance 2:', instance2.addThemUp())

Serializing object methods using ES6 template strings and eval, This example illustrates one method of serializing and recreating class we'll use a class CaveMan, with a property discovered that holds a Date instance, and​  I was having some issues using the above solutions with an "associative array" type object. These solutions seem to preserve the values, but they do not preserve the actual names of the objects that those values are associated with, which can cause some issues.

When you serialize your object in JSON form, your class information will be lost. To prevent it from happening, you have to add a property manually to preserve your original class information; like class name. Then you can use that information bit while deserializing, and restore all information to original class object. Here is a general way to bring JSON back to its original class object:

class Foo{
    constructor(var1, var2){
        // save your class name as property
        this.classname = this.constructor.name;

        this.var1 = var1;
        this.var2 = var2;
    }

    hoo(var3, var4){
        this.var3 = var3;
        this.var4 = var4;
    }

    serialize(){
        return JSON.stringify(this);
    }
}

let foo = new Foo(1, 2);
foo.hoo(3, 4);

//Now we have JSON string:
//'{"classname":"Foo","var1":1,"var2":2,"var3":3,"var4":4}'
let json = foo.serialize();

function deserialize(json){
    //o is [Object object], but it contains every state of the original object
    let o = JSON.parse(json);
    //Get original class instance
    let original_class = eval(o.classname);

    //Create new object of the original class, then restore back property values
    //NOTE: You may not need to pass any parameter to the constructor, since
    //every state of the original object will be restored from o.
    return Object.assign(new original_class(), o);
}

let _foo = deserialize(json);
console.log(_foo instanceof Foo); // returns true;

I also created a small module that works with Node.js and handle nested objects as well, so if you are interested please check the code as well.

Example: Rebuilding Class Instances from JSON Data, Serializing a monster with JSON.stringify() loses all this “class” information, so the deserialized object will have no behavior. function Foo()  Serialization (C#) Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

Serializing JavaScript Objects « null program, Code Issues 14 Pull requests 6 Projects 0 Actions Security 0 Pulse. Serialize and deserialize complex object graphs to and from JSON and Javascript classes. @PavelAlexeev No, you don't neet to include json2.js anymore, unless you are targetting very old browsers: modern browsers include a native implementation of the JSON object. The good thing about json2.js is that it will only kick in if no native object is found.

mobxjs/serializr: Serialize and deserialize complex object , Tagged with discuss, javascript. function serialize (obj: any) { return JSON.​stringify( obj, (_, v) => v Actually, I have now succeeded in deserializing objects (instead of Arrays). The solution is here. GitHub logo patarapolw / any-serialize. Serialize any JavaScript classes, as long as you provides how-to. In Deserialization, it does the opposite of Serialization, which means it converts JSON string to a custom .Net object. In the following code, it creates an instance of BlogSite class and assigns values to its properties. Then we create an instance of DataContractJsonSerializer class by passing the parameter BlogSite class and creating an

What is a best / simplest way to serialize / deserialize JavaScript , it not only deserialize JSON text into a JavaScript object, it also converts it into an instance of the class specified in the context option (similar packages are:  Serialization is a concept in which C# class objects are written or serialized to files. Let' say you had a C# class called Tutorial. And the class has 2 properties of ID and Tutorials name. Serializing can be used to directly write the data properties of the Tutorial class to a file.

Comments
  • Using Object.assign alongside JSON.stringify definitely does the job for an object with native type variables, so thank you very much for this. Is it possible for these to work recursively in objects within this object that also have functions, or will I have to go through the owned objects myself and assign each? It's not the end of the world if I do, at least I'm not doing it for every variables therein!