Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON that contains functions

I have a website that returns a JSON-like data structure like this:

{
    "name":"tom jones",
    "no": 123,
     "storedproc": function(){
                      callbuyer(0123);
                    }
}

I'm getting this data using $.ajax() with dataType "JSON". Unfortunately, my $.ajax() calls the error callback because my data contains a function(). How can I parse this correctly? I really need to store the function in a variable and call it later.

like image 605
Netorica Avatar asked Dec 12 '22 00:12

Netorica


2 Answers

That is simply not legal JSON (as you know given the title of the question) See the offical JSON syntax. The nice thing about real JSON is that one can use JSON.parse which safely wraps an eval call.

While eval could be used, I would suggest revisiting the architecture of your application and find some other way to do what you are trying to do.

In particular, I would have the server return the 0123 only, and let your client keep the logic that lets it know, in certain cases, which functions apply (in the scenario here, the function would be callbuyer).

This should work because you say you want to call the function which is the value of the storedproc later. Since the body of this function contains a call to callbuyer it follows that your client side script knows what callbuyer is. The trick is for your server not to send back arbitrary, unconstrained functions, but rather data that your client can exploit somehow using the knowledge it has about the overall application.

like image 188
Ray Toal Avatar answered Dec 28 '22 18:12

Ray Toal


Could you arrange to have the server return JSON like this:

{"name":"tom jones",
  "no": 123,
 "storeprocFn": callbuyer,
 "arg": "0123"};

Then your callback function can call the callbuyer function and pass arg

like image 40
DavidHyogo Avatar answered Dec 28 '22 18:12

DavidHyogo