Below is the code I am running in my Java compiler:
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
engine.put("person", "{name: 'Bob', favoriteColor: 'red'}");
System.out.println(engine.get("person.name"));
I would expect this to evaluate to "Bob", but instead it gives me null
. If I try printing just the user object, it properly gives me this output:
{name: 'Bob', favoriteColor: 'red'}
Why is person.name
evaluating to null
? Any help would be appreciated!
Apparently the
put
method doesn't evaluate the value passed, but assumes it is meant as a literal. For examplescript.put("test", 5)
will put the literal integer value5
into a variable calledtest
.The second thing that's wrong is that
get
also doesn't evaluate its parameter, but assumes it, too, is the literal name of the variable.However, it is possible to do what you are trying to accomplish. Try this: