How to serialize & deserialize JavaScript objects?

I need to serialize and deserialize JavaScript objects to store them in a DB.

Note that these objects contain functions, so I can't store them as JSON, so I can't use json2.js.

What's the state of the art in [de]serialization of JavaScript objects (in JavaScript of course).

4

6 Answers

In general, there's no way (in a browser) to serialize objects with functions attached to them: Every function has a reference to its outer scope, that scope won't exist when you deserialize it, so serialized references to that scope will be invalid.

What I would do is use the built-in (or json2.js) JSON.stringify and JSON.parse functions with the replacer and reviver parameters. Here's a partial example of how it would work:

JSON.stringify(yourObject, function(name, value) { if (value instanceof LatLng) { // Could also check the name if you want return 'LatLng(' + value.lat() + ',' + value.lng() + ')'; } else if (...) { // Some other type that needs custom serialization } else { return value; }
});
JSON.parse(jsonString, function(name, value) { if (/^LatLng\(/.test(value)) { // Checking the name would be safer var match = /LatLng\(([^,]+),([^,]+)\)/.exec(value); return new LatLng(match[1], match[2]); } else if (...) { ... } else { return value; }
});

You can use any serialization format you want in your custom types. The "LatLng(latitude,longitude)" format is just one way of doing it. You could even return a JavaScript object that can be serialized to JSON natively.

3

You don't want to serialize logic such as functions.

If you have to update your logic / js functions in the future, you don't (always) want the older logic to be loaded back with the data neccessarily. Beware.

use gserializer:

the code in google :

GSerializer is a javascript library to serialize/deserialize javascript objects to and from strings, for persistance in say, a Cookie. Unlike many other implementations, GSerializer can also serialize functions and non-JSON notation.

4

On Node.js, there is also the JASON package.

Here is the example:

var JASON = require("JASON");
str = JASON.stringify(obj);
obj = JASON.parse(str);

Install the package by: npm install JASON.

If you're using ES6 versions of Node, you can check out a small package I wrote called JSOFF. It's the JavaScript Object-Function Format; a drop-in replacement for JSON that handles functions.

It's super tiny and simple, so Babeljs or Browserify may be your friends.

Install via: npm install jsoff or yarn add jsoff.

Here is the example how to create an object with functions:

const JSOFF = require('jsoff');
var obj = { abc: 123, def: function (a,b) { return a * 2 + b * 3; }, ghi: a => { return a * 2 }, jkl: (a,b) => { return ((d,e) => { return a*d + b*e })(2,4) }
};
var str = JSOFF.stringify(obj);
// str is now:
// '{"abc":123,"def":"function (a,b) { return a * 2 + b * 3; }","ghi":"a => { return a * 2 }","jkl":"(a,b) => { return ((d,e) => { return a*d + b*e })(2,4) }"}');
});
var clone = JSOFF.parse(str);
clone.def(10,5) // 35
clone.ghi(5) // 10
clone.jkl(10,20) // 100

I wouldn't serialize JS functions because of security reasons. Through a public API all kinds of nasty things could be sent to the database. As for deserialisation I've got a different approach. I'm mixing model objects defined on client side with the data coming from JSON. I have a small tool to do that, take a look at it on GitHub at khayll/jsonmix.

JsonMix provides a kind of deserialisation from JSON into JavaScript Objects complete with functions.

It would look like something:

//model definition (just an example)
var LatLng = function() {}
LatLng.prototype.getMapTypeId = function() { return this.mapTypeId;
}
//deserializing done like this
var result = JSMix(jsonString).withObject(LatLng.prototype, "latLngs").build();
//all items in the latLngs collection have the functions coming from the model
console.log(result.latLngs[5].getMapTypeId());
4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like