Using jsonPath to filter data ... what's the Camunda syntax?

Hi folks, I have a Spin JSON var (shown below) in which all elements have the same set of fields.

I want to query the JSON to extract a subset of elements and create a process variable from the result. For instance, get all elements whose groupId == “A” (i.e. a subset of the original JSON)

I’m doing this in a script task (inline Javascript code below) but when I start the process I get error, "cannot serialize object in variable ‘myData’. How should I set up the jsonPath query? Alternatively, how should I manipulate ‘result’ to get it into a process variable (I’ve tried S(result) with no success)

Contents of JSON variable ‘myData’:

[
  {
    "workId": 1,
    "orderIdType": "PO",
    "groupId": "A"
  },
  {
    "workId": 2,
    "orderIdType": "Other",
    "groupId": "A"
  },
  {
    "workId": 3,
    "orderIdType": "Other",
    "groupId": "B"
  },
  {
    "workId": 4,
    "orderIdType": "PO",
    "groupId": "B"
  }
]

Contents of the script task (Javascript, inline script):

var myQuery = "$.[?(@.groupId==\'A\')]";
var result = myData.jsonPath(myQuery);
execution.setVariable('queryResult', result);

Much appreciated!

Found my answer. Two things were missing:

  1. The jsonPath() function must be suffixed with .elementList() to produce a JSON-like result

  2. The result of jsonPath needs to be processed by JSON.parse and JSON.stringify before it can be sent to S() and saved as a process var. Here’s the inline Javascript code that actually works, including the JSON creation for easy reference:

    var rawData="[{“workId”:1,“orderId”:“1044”},{“workId”:2,“orderId”:“1044”},{“workId”:3,“orderId”:“1080”},{“workId”:4,“orderId”:“1081”}]";
    var jsonData=S(rawData);
    var targetVal = 3;
    var query = “$.[?(@.workId<” + targetVal + “)]”;
    var queryResult = jsonData.jsonPath(query).elementList();
    var mySpin = S(JSON.stringify(JSON.parse(queryResult)));
    execution.setVariable(‘finalOutput’, mySpin);

3 Likes