0

I have a json object

"a1":
{
"b1": "val1",
 "b2": "function() {return null}",
 "c1": "{}"
}

This function needs to be passed to run a rethink-db query. This function a1.b1 needs to be passed

r.db(database).table(table).indexCreate(indexname, a1.b2, a1.c1)

When I run the query I get the error msg: 'Expected type FUNCTION but found DATUM:\n"function() {return null;}"',

Please suggest a fix for this.

Puja
  • 17
  • 5
  • how about adding another line var returnNull = function() {return null}; and update your string to 'returnNull' – g2000 Nov 02 '15 at 21:33
  • Does this help? http://www.sitepoint.com/call-javascript-function-string-without-using-eval/ – Pikamander2 Nov 02 '15 at 21:33
  • using a Set or Map would help – baao Nov 02 '15 at 21:38
  • @Pikamander2 I need to access it from the json object only. – Puja Nov 02 '15 at 21:40
  • Functions are not valid JSON. You literally cannot send that over the wire. – Jared Smith Nov 02 '15 at 21:43
  • @JaredSmith - It may not be a good idea to do so, but it is possible – Pikamander2 Nov 02 '15 at 21:44
  • 1
    @JaredSmith technically it isn't a function, it's a string. :) – Kevin B Nov 02 '15 at 21:44
  • 2
    There are no "good" solutions to this, your only real options are: do something else entirely, or eval. I'd lean toward the side of do something else entirely, meaning, not passing a function expression (is that the right term?) as a string in json. – Kevin B Nov 02 '15 at 21:46
  • True, but you cannot convert it without `eval`/`new Function` etc, making it pretty pointless unless you're *desperate* to get it done at the cost of both performance and security. If you really need to load a function dynamically, you should append a script tag with the `src` attribute set to the file with the function. And yeah, what @KevinB said. – Jared Smith Nov 02 '15 at 21:46

1 Answers1

1

On one note, you usually shouldn't be sending functions across as JSON, which is the genesis of your problem. However, ignoring that for now, you can do eval:

r.db(database).table(table).indexCreate(indexname, eval('('+a1.b2+')'), {});

Careful with eval though. There are security issues, etc.

For some additional ways of evaluating a function from a string, I'd recommend checking out this question.

Community
  • 1
  • 1
Josh Beam
  • 19,292
  • 3
  • 45
  • 68