Skip to content

Instantly share code, notes, and snippets.

@thenoseman
Created June 19, 2014 11:45
Show Gist options
  • Save thenoseman/d19aeb6c06929332f132 to your computer and use it in GitHub Desktop.
Save thenoseman/d19aeb6c06929332f132 to your computer and use it in GitHub Desktop.
JSON serializer allowing functions to be serailized
/*eslint no-new-func:0*/
"use strict";
var JSONF = {
stringify: function(object) {
return JSON.stringify(object, this._functionSerializer);
},
parse: function(jsonString) {
return JSON.parse(jsonString, this._functionDeserializer);
},
_functionSerializer: function(key, value) {
if (typeof (value) === "function") {
return value.toString();
}
return value;
},
_functionDeserializer: function(key, value) {
if (key === "") {
return value;
}
if (typeof value === "string") {
var rfunc = /function[^\(]*\(([^\)]*)\)[^\{]*{([^\}]*)\}/;
var match = value.match(rfunc);
if (match) {
var args = match[1].split(',').map(function(arg) {
return arg.replace(/\s+/, '');
});
return new Function(args, match[2]);
}
}
return value;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment