LinkedHashMap to JSON in Nashorn

Dear Camunda community,

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.:

function replacer(key, value) {
return value.documentType || value.taxCode || value;

I have already tried nashorn’s Java.from(), but it cannot cast LinkedHashMap to JS object.

Thank you in advance.

Best regards,


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')

// 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())
// 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')

Hi @StephenOTT

Brilliant. Exactly what is needed!!!


1 Like

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:

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.

Link to the Java docs: JsonUtil (camunda BPM - engine 7.14.0 API)


@SeRGiOJoKeR11 thanks for the update! :star_struck:
You saved me time, I don’t know Java, manipulating JSON is a horror for the Camunda beginner.

Thanks! It works perfectly.