Best way to serialize/unserialize objects in JavaScript?

Viewed 155835

I have many JavaScript objects in my application, something like:

function Person(age) {
    this.age = age;
    this.isOld = function (){
        return this.age > 60;
    }
}
// before serialize, ok
var p1 = new Person(77);
alert("Is old: " + p1.isOld());

// after, got error Object #<Object> has no method 'isOld'
var serialize = JSON.stringify(p1);
var _p1 = JSON.parse(serialize);
alert("Is old: " + _p1.isOld());

See in JS Fiddle.

My question is: is there a best practice/pattern/tip to recover my object in same type it was before serialization (instances of class Person, in this case)?

Requirements that I have:

  • Optimize disk usage: I have a big tree of objects in memory. So, I don't want to store functions.
  • Solution can use jQuery and another library to serialize/unserialize.
10 Answers

I've added yet another JavaScript serializer repo to GitHub.

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().

https://github.com/iconico/JavaScript-Serializer

You can create an empty instance of of your class and assign values to it with Object.assign.

let p1 = new Person(77);
let serialized = JSON.stringify(p1);
let deserialized = Object.assign(new Person(), JSON.parse(serialized))

I tried to do this with Date with native JSON...

function stringify (obj: any) {
  return JSON.stringify(
    obj,
    function (k, v) {
      if (this[k] instanceof Date) {
        return ['$date', +this[k]]
      }
      return v
    }
  )
}

function clone<T> (obj: T): T {
  return JSON.parse(
    stringify(obj),
    (_, v) => (Array.isArray(v) && v[0] === '$date') ? new Date(v[1]) : v
  )
}

What does this say? It says

  • There needs to be a unique identifier, better than $date, if you want it more secure.
class Klass {
  static fromRepr (repr: string): Klass {
    return new Klass(...)
  }

  static guid = '__Klass__'

  __repr__ (): string {
    return '...'
  }
}

This is a serializable Klass, with

function serialize (obj: any) {
  return JSON.stringify(
    obj,
    function (k, v) { return this[k] instanceof Klass ? [Klass.guid, this[k].__repr__()] : v }
  )
}

function deserialize (repr: string) {
  return JSON.parse(
    repr,
    (_, v) => (Array.isArray(v) && v[0] === Klass.guid) ? Klass.fromRepr(v[1]) : v
  )
}

I tried to do it with Mongo-style Object ({ $date }) as well, but it failed in JSON.parse. Supplying k doesn't matter anymore...

BTW, if you don't care about libraries, you can use yaml.dump / yaml.load from js-yaml. Just make sure you do it the dangerous way.

I've made an npm module named esserializer to solve this problem: save JavaScript class object values during serialization, in plain JSON format, without storing any functions. During the serialization, the only overhead incurred is saving the class names information. Thus, the disk usage is optimized.

Later on during the deserialization stage, esserializer can recursively deserialize object instance, with all types/functions information retained. It works in both browser and Node.js environment.

In the OP's case, the code would be pretty easy:

var ESSerializer = require('esserializer');

function Person(age) {
    this.age = age;
    this.isOld = function (){
        return this.age > 60;
    }
}
// before serialize, ok
var p1 = new Person(77);
alert("Is old: " + p1.isOld());

// serialize
var serializedText = ESSerializer.serialize(p1);
//...do something, or send the above serializedText to another JavaScript environment.
// deserialize
var deserializedObj = ESSerializer.deserialize(serializedText, [Person]);
alert("Is old: " + deserializedObj.isOld());

the deserializedObj is a Person instance, which contains all values/functions/superclasses information.

Wish it could help.

Related