How to convert Java Map to a basic Javascript object?

Jon Carlson picture Jon Carlson · Sep 22, 2011 · Viewed 30.3k times · Source

I'm starting to use the dynamic rhinoscript feature in Java 6 for use by customers who are more likely to know Javascript than Java.

What is the best way to pass a Map (associative array, javascript obj, whatever) into Javascript so the script-writers can use the standard Javascript dot notation for accessing values?

I'm currently passing a java.util.Map of values into the script, however then the script writer has to write "map.get('mykey')" instead of "map.mykey".

Basically, I want to do the opposite of this question.

Answer

Jon Carlson picture Jon Carlson · Sep 27, 2011

I took the Java NativeObject approach and here is what I did...

// build a Map
Map<String, String> map = new HashMap<String, String>();
map.put("bye", "now");

// Convert it to a NativeObject (yes, this could have been done directly)
NativeObject nobj = new NativeObject();
for (Map.Entry<String, String> entry : map.entrySet()) {
    nobj.defineProperty(entry.getKey(), entry.getValue(), NativeObject.READONLY);
}

// Get Engine and place native object into the context
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("javascript");
engine.put("map", nobj);

// Standard Javascript dot notation prints 'now' (as it should!)
engine.eval("println(map.bye);");