1

I have this code stored as string:

{
  "func": function (field) {
    var date = getDate(field);
    return date != -1;
  },
  "somethingElse": "Message",
  "somethingElse2": "Message2"
}

Is there a way to convert it to an object? JSON.parse don't allow functions.

Nauzet
  • 661
  • 8
  • 20

4 Answers4

2

As Durendal already said, you have to deliver your function as a string that can be handled by JSON.parse. After that you can call your function with eval:

var string = '{"func":"function (field) {return field;}","somethingElse": "Message","somethingElse2":"Message2"}';

var jsonObject = JSON.parse(string);
var func = eval("("+jsonObject["func"]+")");

document.write(func("abc"));

You may also be interested in this question: JavaScript eval() "syntax error" on parsing a function string

Community
  • 1
  • 1
Fidel90
  • 1,828
  • 6
  • 27
  • 63
1

Your string shoud look like this :

var string = '{"func":"function (field) {var date = getDate(field);return date != -1;}","somethingElse": "Message","somethingElse2":"Message2"}';

var jsonObject = JSON.parse(string);

https://jsfiddle.net/pc6hdk1y/

AshBringer
  • 2,614
  • 2
  • 20
  • 42
1

First of all, to even store the method like this you need to use replacer function

var text = JSON.stringify(a, function(k,v){
  return typeof v == "function" ? v.toString() : v;
})

Now, to get the function back, you need to use the reviver function

JSON.parse(text,function(k,v){
  console.log(v);

  return typeof v == "string" && v.indexOf("function") == 0 ? new Function(v.substring(v.indexOf("{")+1, v.lastIndexOf("}"))) : v;
})
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • Is there a reason why `JSON` does not handle functions like this out of the box? – Fidel90 Apr 26 '16 at 09:10
  • 1
    @Fidel90 I don't think it is secure to parse an arbitrary string into executable method. Secondly, JSON doesn't know if the value is a method or not, since all it gets is a string. – gurvinder372 Apr 26 '16 at 09:11
  • sadly seems the function arguments are not being restored on the parse – Nauzet Apr 26 '16 at 09:26
  • @Ralstlin wait, let me do something about that as well. – gurvinder372 Apr 26 '16 at 09:29
  • 1
    @Ralstlin it seems to me that unless function is using `arguments` object inside the function, it won't be able to use the variable arguments without `eval` – gurvinder372 Apr 26 '16 at 10:11
0

If you want to reuse the function you probably need to do it like

var data = {
                      "func": ["field", "var date = getDate(field); return date != -1;"],
             "somethingElse": "Message",
            "somethingElse2": "Message2"
           },
   jData = JSON.stringify(data),
   pData = JSON.parse(jData),
    func = new Function(pData.func[0],pData.func[1]);
document.write("<pre>" + func + "</pre>");
Redu
  • 25,060
  • 6
  • 56
  • 76