Reputation: 46
I was a bit surprised when raising an exception with this simple expression in Nashorn (JDK8 from Oracle, latest) :
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByName("js");
engine.eval("{a:1,b:2}");
Which gives
javax.script.ScriptException: :1:6 Expected ; but found : {a:1,b:2}; ^ in at line number 1 at column number 6 at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470) at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:537) at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:524) at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402) at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155) at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
Any idea ?
Upvotes: 2
Views: 303
Reputation: 35232
Assuming this functionality is similar to javascript eval
, you're getting this error because eval("{a:1,b:2}")
evaluates {}
as a code block and not as an object literal.
eval("{a:1,b:2}")
That code is equivalent to:
{
a: 1,
b: 2
}
The error is being thrown in the b: 2
line. Here, a
becomes a labeled statement within a new {}
block. So, if you had created an object literal with just one property, this would've worked.
eval("{a:1}") // no errors
If you want an object literal, then assign it to a variable
eval("var obj = {a:1,b:2}")
console.log(obj)
Upvotes: 2
Reputation: 46
Thanks to adiga, using
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByName("js");
engine.eval("({a:1,b:2})");
solved my problem. (Note the parenthesis which disable the "code block")
Upvotes: 0