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.

1
  • replace }, with }(), Commented Apr 26, 2016 at 8:46

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

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;
})

5 Comments

Is there a reason why JSON does not handle functions like this out of the box?
@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.
sadly seems the function arguments are not being restored on the parse
@Ralstlin wait, let me do something about that as well.
@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
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>");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.