5

I have a JavaScript object in String form (actually coming from database) which I need to pass to a Javascript function using Nashorn (Java 8). The Engine treats the parameter passed as a string in javascript. I want it to identify it as a Javascript object.

Below is the code snippet:

String script = "function genData(dataModel) { return 'hello world '+ dataModel.url.value + ' done'; }";  

//"{url : {value : "abc.com",type  : "string"},layout : {value : "",type  : "string"}}";  

String dataModel = "{url : {value : \"abc.com\",type  : \"string\"},layout : {value : \"\",type  : \"string\"}}";

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
Invocable inv = (Invocable) engine;
result = inv.invokeFunction("genData", dataModel);

The error I get is:
javax.script.ScriptException: TypeError: Cannot read property "value" from undefined in at line number 1

2
  • your dataModel is not a valid string literal.... Commented May 12, 2017 at 6:36
  • Well the idea was to show how the javascript object looks like and make it less cryptic. I have moved it as a comment and escaped the string if that helps Commented May 16, 2017 at 23:16

2 Answers 2

5

You could convert dataModel string as JSON first - either in the function itself or elsewhere and then pass it.

Example:

String dataModel = ...;
// convert the string as a JSON object
engine.put("dataModel", dataModel);
JSObject obj = (JSObject)engine.eval("JSON.parse(dataModel)");
...
// dataModel is a script object - as it is a result of JSON.parse
// pass it as parameter for genData
inv.invokeFunction("genData", obj);
Sign up to request clarification or add additional context in comments.

Comments

2

If your dataModel is a simple Java Map then you can pass it to invokeFunction directly as a parameter. For more advanced uses your parameter should implement the Bindings interface.

To make this easier I wrote a library called json:

Example:

    Json j = new Json("a", 5);
    Double result = (Double) eng.eval("a+1", j);

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.