How to pass Javascript Object from Java to Javascript using Nashorn

java, javascript, nashorn, scriptengine

Solution

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

Problem

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

Original source