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

前端 未结 9 1885
一个人的身影
一个人的身影 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:10

    Technically this is not JSON, I can also hardly imagine why would you want to do this, but try the following hack:

    x.key2 = x.key2.toString();
    JSON.stringify(x)  //"{"key1":"xxx","key2":"function (){return this.key1}"}"
    

    Of course the first line can be automated by iterating recursively over the object. Reverse operation is harder - function is only a string, eval will work, but you have to guess whether a given key contains a stringified function code or not.

提交回复
热议问题