Created
March 17, 2016 06:04
-
-
Save lccxx/3a234c1a81664495c39f to your computer and use it in GitHub Desktop.
js obj with function stringify
This file contains hidden or 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
function obj2str(obj) { | |
var fString = function(objj) { | |
if (!objj) return objj; | |
var newObj = Array.isArray(objj) ? [] : {} | |
Object.keys(objj).map(function(k) { | |
if (typeof(objj[k]) == "function") newObj[k] = objj[k].toString(); | |
else if (typeof(objj[k]) == "object") newObj[k] = fString(objj[k]); | |
else newObj[k] = objj[k]; | |
}) | |
return newObj; | |
}; | |
var newObj = fString(obj); | |
return JSON.stringify(newObj); | |
} | |
function str2obj(str) { | |
var fsObject = function(objfs) { | |
if (!objfs) return objfs; | |
Object.keys(objfs).map(function(k) { | |
if (/^function/.test(objfs[k])) eval("objfs[k] = " + objfs[k]); | |
else if (typeof(objfs[k]) == "object") fsObject(objfs[k]); | |
}) | |
}; | |
var obj = JSON.parse(str); | |
fsObject(obj); | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment