Created
June 19, 2014 11:45
-
-
Save thenoseman/d19aeb6c06929332f132 to your computer and use it in GitHub Desktop.
JSON serializer allowing functions to be serailized
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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