0

So I have a js object with the following sample key-value pairs.

var serial = { 
 open: function(a, b) { 
       do something..
},

close: function (a,b) { 
       do something
}

}

As seen above the value for the keys are js functions. Due to some requirements I had to convert the whole object to string. I had used the following code to convert it to string:

var json = JSON.stringify(window.serial, function(key, value) {
    if (typeof value === 'function') {
        return value.toString();
    } else {
        return value;
    }   
});

How can I convert the strings back to function prototypes and store it in the same obj?

krishnanspace
  • 403
  • 1
  • 7
  • 17
  • 3
    Sounds like an XY problem: why do you ever need to store a function as a string? – Terry Jan 07 '20 at 10:21
  • @Terry Its due to some requirements/complexities – krishnanspace Jan 07 '20 at 10:22
  • Sounds like an odd requirement. Normally, you'd just send the *data*, no functions or methods, and then initialise an object using the data. The object knows about the methods it needs. – VLAZ Jan 07 '20 at 10:26
  • 2
    [you have a similar question posted here](https://stackoverflow.com/questions/36517173/how-to-store-a-javascript-function-in-json) – tit Jan 07 '20 at 10:27
  • What exactly is "*do something*"? Can the function (closure) even be properly represented as a string? – Bergi Jan 07 '20 at 10:27
  • @Bergi Its been converted to a string without any problem. Its just that I need to convert it back to a Function – krishnanspace Jan 07 '20 at 10:30
  • 1
    @krishnanspace `return ""` also converts the function to a string without any problem. But a string that cannot be converted back to a function actually doing what you want. It could, again, trivially be converted to the empty function of course. – Bergi Jan 07 '20 at 10:33

1 Answers1

-1

eval will convert string back to function

var str = "function fn(){ console.log('loggin function') }";

eval(str);

fn();
Akash Shrivastava
  • 1,365
  • 8
  • 16
  • `eval()` should almost never be used. – Mitya Jan 07 '20 at 10:24
  • @Utkanos Actually, `eval` is the sensible choice to convert a string to executable code. – Bergi Jan 07 '20 at 10:25
  • 1
    @Bergi I agree with you. However, the thing is that most times I've not seen a *sensible* reason to transfer functions as strings. A lot of times it's an XY problem that somebody is trying to solve and has decided "Hey, I can turn this to a string" when there are better alternatives. However, that's not to say there *aren't* times you'd want to convert text into executable code. You can serialise functionality and send push it over a websocket, so it gets executed on a different machine, for example. It's a simple and effective way to get distributed computation going. – VLAZ Jan 07 '20 at 10:30