How to set and get variables with inline scripts without getting errors

I am new to camunda and I run it with via docker. I try to implement a process only by using the camunda modeler and a bpmn file. My process requires some scripting but I do not get how scripting is supposed to work with more complex data stored in variables as they seem to be not avaiable anymore as soon as I store them.

I’ve tried to create an array with javascript and save it to a new variable:

var listAsJsonStr = execution.getVariable(listJson) //[ex1,ex2]
var listJson = JSON.parse(listAsJsonStr);
var myList = new Array();
for (var i = 0; i < listJson.length; i++) {
myList.push(listJson[i]);
}
execution.setVariable(‘accessibleList’, myList);

I noticed that the variable is not being saved as an array or a list but is somehow serialized with a json format. I see this type with this content by inspecting it in the cockpit:

jdk.nashorn.api.scripting.ScriptObjectMirror<java.lang.String,java.lang.Object>
{0:ex1,1:ex2}

However, as soon as I try to get that variable I get an error:

execution.getVariable("accessibleVariable");

Deserialization Error: Cannot deserialize object in variable ‘accessibleList’: SPIN/JACKSON-JSON-01007 Cannot construct java type from string ‘jdk.nashorn.api.scripting.ScriptObjectMirror<java.lang.String,java.lang.Object>’

I do not know how to store and retrieve more complex data types with the modeler.

Even if I set a variable in the modeler by providing one in an output parameter section, then set a new string value for this parameter and after that want to access this parameter via ${VariableName} the variable is not being found by the engine anymore although it is correctly displayed as ‘string’ in the cockpit. Edit: I tried to fetch that variable in an expression within a signal event. It seems like I had to explicitly provide the parameter as input parameter? Seems strange.

See Reading JSON | docs.camunda.org on working with JSON Arrays and SPIN (the lib that wraps JSON used by Camunda).

var myJsonString = execution.getVariable('myJsonString') // String
var parsedJsObj = JSON.parse(myJsonString) // JS Array

var mySpinObject = S(JSON.stringify(parsedJsObject)) // SPIN object
var elements = mySpinObject.elements() // Collection / List
var firstElement = elements.get(0) // element from the list

elements.append("My Additional Value")

execution.setVariable("mySpinJson", mySpinObject) // This will save the variable as Type JSON/byte array in the db


If you are working with an object, see the docs for property accessors.

also can look at Nashorn (the JS engine that Camunda uses for JS execution) for other helpers (such as the for each loop): Java 8 Nashorn Tutorial

2 Likes