LinkedHashMap to JSON in Nashorn


#1

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,
Ilya


#2

@Ilya_Malyarenko


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

#3

Hi @StephenOTT

Brilliant. Exactly what is needed!!!

Cheers,
Ilya