Would appreciate your advice on converting a variable stored as LinkedHashMap object into JSON using JavaScript in Camunda. LinkedHashMap variable is created via REST API and later on I need to parse JSON to prune some leafs in a tree.
I could walk through LinkedHashMap programmatically of course to accomplish this, however I’d like to use nashorn’s magic of JSON.parse(variable, replacer) where replacer is a function to do some data conversion from JSON objects to Strings, i.e.:
var system = java.lang.System
var LinkedHashMap = Java.type("java.util.LinkedHashMap")
var lhm = new LinkedHashMap()
lhm.put('key1', 'value1')
lhm.put('key2', 'value2')
lhm.put('key3', 'value3')
system.out.println("LinkedHashMap:");
system.out.println(lhm.toString());
// prints: {key1=value1, key2=value2, key3=value3}
var JSONObject = Java.type('org.camunda.bpm.engine.impl.util.json.JSONObject')
var myJson = JSON.parse(new JSONObject(lhm).toString())
system.out.println(JSON.stringify(myJson))
// prints: {"key1":"value1","key2":"value2","key3":"value3"}
//FYI for when you are dealing with a list/array;
// be aware of: // var JSONArray = Java.type('org.camunda.bpm.engine.impl.util.json.JSONArray')
As of Camunda 7.14.0, ‘org.camunda.bpm.engine.impl.util.json.JSONObject’ doesn’t exist or perhaps has been refactored out.
Here is how you would do it:
Blockquote
var JsonUtil = Java.type(‘org.camunda.bpm.engine.impl.util.JsonUtil’);
var engagement = JsonUtil.asString(engagement); //engagement here is a java.util.HashMap
print(engagement); // this is a stringified JSON
var income = JSON.parse(engagement1).income; // the dot notation can be used on the result of JSON.parse, obvs, because it is a JS object.
print(JSON.stringify(income)); //stringifying is needed to be able to print a JS object. Otherwise one gets [object Object].
Note: this code has been executed on GraalJS 21.0.0. Although, I haven’t tried it on Nashorn I don’t see why it would not work on it.