4

I'm building a json object in java. I need to pass a function into my javascript and have it validated with jquery $.isFunction(). The problem I'm encountering is I have to set the function in the json object as a string, but the json object is passing the surrounding quotes along with object resulting in an invalid function. How do I do this without having the quotes appear in the script.

Example Java

JSONObject json = new JSONObject();
json.put("onAdd", "function () {alert(\"Deleted\");}");

Jquery Script

//onAdd output is "function () {alert(\"Deleted\");}" 
//needs to be //Output is function () {alert(\"Deleted\");} 
//in order for it to be a valid function.
if($.isFunction(onAdd)) { 
    callback.call(hidden_input,item);
}

Any thoughts?

Code Junkie
  • 7,602
  • 26
  • 79
  • 141

3 Answers3

9

You can implement the JSONString interface.

import org.json.JSONString;

public class JSONFunction implements JSONString {

    private String string;

    public JSONFunction(String string) {
        this.string = string;
    }

    @Override
    public String toJSONString() {
        return string;
    }

}

Then, using your example:

JSONObject json = new JSONObject();
json.put("onAdd", new JSONFunction("function () {alert(\"Deleted\");}"));

The output will be:

{"onAdd":function () {alert("Deleted");}}

As previously mentioned, it's invalid JSON, but perhaps works for your need.

Mike
  • 501
  • 3
  • 5
3

You can't. The JSON format doesn't include a function data type. You have to serialise functions to strings if you want to pass them about via JSON.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Running

onAdd = eval(onAdd);

should turn your string into a function, but it's buggy in some browsers.

The workaround in IE is to use

onAdd = eval("[" + onAdd + "]")[0];

See Are eval() and new Function() the same thing?

Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • hmm so nothing stable, what about just removing the start and end quotes? – Code Junkie Jun 01 '12 at 16:35
  • @George, if you remove the quotes, it's not JSON. However, If you are rendering the HTML in Java using the JSON object, you can just `out.println(json.get("onAdd"))` and it would print without quotes – Ruan Mendes Jun 01 '12 at 17:16