Last active
November 21, 2016 14:03
-
-
Save SergProduction/18517413983909879dd5e6130ec3405f to your computer and use it in GitHub Desktop.
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
var JSONfn = {}; | |
JSONfn.stringify = function (obj) { | |
return JSON.stringify(obj, function (key, value) { | |
var fnBody; | |
if (value instanceof Function || typeof value == 'function') { | |
fnBody = value.toString(); | |
if (fnBody.length < 8 || fnBody.substring(0, 8) !== 'function') { //this is ES6 Arrow Function | |
return '_NuFrRa_' + fnBody; | |
} | |
return fnBody; | |
} | |
if (value instanceof RegExp) { | |
return '_PxEgEr_' + value; | |
} | |
return value; | |
}); | |
}; | |
JSONfn.parse = function (str, date2obj) { | |
var iso8061 = date2obj ? /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/ : false; | |
return JSON.parse(str, function (key, value) { | |
var prefix; | |
if (typeof value != 'string') { | |
return value; | |
} | |
if (value.length < 8) { | |
return value; | |
} | |
prefix = value.substring(0, 8); | |
if (iso8061 && value.match(iso8061)) { | |
return new Date(value); | |
} | |
if (prefix === 'function') { | |
return eval('(' + value + ')'); | |
} | |
if (prefix === '_PxEgEr_') { | |
return eval(value.slice(8)); | |
} | |
if (prefix === '_NuFrRa_') { | |
return eval(value.slice(8)); | |
} | |
return value; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment