Is there any possibility to have JSON.stringify preserve functions?

前端 未结 9 1884
一个人的身影
一个人的身影 2020-12-01 05:14

Take this object:

x = {
 \"key1\": \"xxx\",
 \"key2\": function(){return this.key1}
}

If I do this:

y = JSON.parse( JSON.st         


        
9条回答
  •  半阙折子戏
    2020-12-01 06:03

    I ran into the same problem, There was another post similar to yours found json-stringify-function. the following may be useful to you:

    var JSONfn;
    if (!JSONfn) {
        JSONfn = {};
    }
    
    (function () {
      JSONfn.stringify = function(obj) {
        return JSON.stringify(obj,function(key, value){
                return (typeof value === 'function' ) ? value.toString() : value;
            });
      }
    
      JSONfn.parse = function(str) {
        return JSON.parse(str,function(key, value){
            if(typeof value != 'string') return value;
            return ( value.substring(0,8) == 'function') ? eval('('+value+')') : value;
        });
      }
    }());
    

    Code Snippet taken from Vadim Kiryukhin's JSONfn.js or see documentation at Home Page

提交回复
热议问题