Skip to content

Instantly share code, notes, and snippets.

@lccxx
Created March 17, 2016 06:04
Show Gist options
  • Save lccxx/3a234c1a81664495c39f to your computer and use it in GitHub Desktop.
Save lccxx/3a234c1a81664495c39f to your computer and use it in GitHub Desktop.
js obj with function stringify
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