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.nameevaluating to null? Any help would be appreciated!
Apparently the
putmethod doesn't evaluate the value passed, but assumes it is meant as a literal. For examplescript.put("test", 5)will put the literal integer value5into a variable calledtest.The second thing that's wrong is that
getalso 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: