0

I need to return the following in a custom REST API I am building using Jackson. The following is simply a Javascript function. Is there a way to return a javascript function as is? Without returning it as string, and then having to parse it on the front end.

{
    yFormat: (timestamp) => { return date.getDurationValue(timestamp); }
}
coffeeak
  • 2,980
  • 7
  • 44
  • 87
  • 2
    No, it's not possible. You are transferring JSON and there are no functions in that - it's just data serialised into text. – VLAZ Jul 22 '19 at 13:44
  • On a side note, why would you even need to send that code from the backend? This seems like it belongs to the front-end and the backend shouldn't be concerned with what code the front-end would be running. – VLAZ Jul 22 '19 at 13:45
  • JSON has string, array, object ect.. It does not have the ability to serialize functions directly. – stacktraceyo Jul 22 '19 at 13:45
  • return as string...and look at that post https://stackoverflow.com/questions/4442752/how-do-i-convert-a-json-string-to-a-function-in-javascript – maximelian1986 Jul 22 '19 at 13:47
  • execute the method on the server side? – Joey Gough Jul 22 '19 at 14:07

1 Answers1

1

So you create a function and use toString() to get it as string. Then you add it to you object and create json string from it. In handler you convert it back to function and use it.

var testFunc = function(e){alert(e);}
var funcAsString = testFunc.toString();
alert(funcAsString);
var json = { "one": 700, "two": funcAsString };
var parameters = JSON.parse( JSON.stringify(json));
eval( 'var func = ' + parameters.two );
func( 'test' ); // alerts "test"

Used How do I convert a JSON string to a function in javascript? post to create that solution.

maximelian1986
  • 2,308
  • 1
  • 18
  • 32
  • 2
    Al tough it is a solution it is not recommended to use eval. Rethinking the design is better in most cases. – Mark Baijens Jul 22 '19 at 14:00
  • In this case `eval` is even more dodgy than usual. Namely, what is `date`? It's supposed to be *something* but what exactly - the front-end is the one supposed to ensure it's there and in scope yet it's the backend with any knowledge of that variable. – VLAZ Jul 22 '19 at 14:13