Search code examples
muledataweavemulesoftanypoint-studiomule4

Create a JSON Object based on input parameter in MuleSoft DataWeave 2.0


So I have a REST API which can have there input Params: START, STOP, RESTART. Start and Stop are distinct operations for the REST API but RESTART essentially means STOP and START. Hence I want to create a Dynamic JSON of either 1 node or 2 nodes based on the operation chosen For e.g. For START/STOP the JSON will be:

{ "appID": "1234",
   "operation": "START"}

OR

{ "appID": "1234",
   "operation": "STOP"}

While for RESTART it be be like:

{ "appID": "1234","operation": "STOP"},{ "appID": "1234","operation": "START"}

I can then loop through this array and call my API once or twice.However I am at a loss to understand how do I create this JSON dynamically in data weave based on the Operation param passed as an input to the REST API call.I have tried to create a variable with 2 node JSON nodes and then try too loop but that doesn't seem to be working.

I tried something like this:

var count = 0
var appID = "1234567890"
var op = "START"
---
(operation map ((item, index) -> {
    "appID": appID,
    "operation": if(op=='START' and index == 0) "START"
                 else if(op=='STOP' and index==0) "STOP" 
                 else if(op=='RESTART' and index==0) "STOP" 
                 else if(op=='RESTART' and index==1) "START" 
                 else ''
})) [ 0 to operation.totalcount - count ]

where the value of Count is either 0 or 1 based on the operation


Solution

  • If I understand correctly if the input value operation is "RESTART" then the script should return an array of elements start and stop, if "START" just a start element and if "STOP" just a stop element. I assume the output is always an array.

    For this script the variable op represents the input. I use the value of op to return the operation if it is not "RESTART". If it is I return "STOP" first and add a second element for "START".

    %dw 2.0
    output application/json
    var appID = "1234567890"
    var op = "RESTART"
    ---
    [
        {
            "appID": appID,
            "operation": if(op !='RESTART') op
                        else "STOP" 
        }
    ] ++ if (op =='RESTART') [{
            "appID": appID,
            "operation": "START" 
        }] else []
    
    

    Output:

    [
      {
        "appID": "1234567890",
        "operation": "STOP"
      },
      {
        "appID": "1234567890",
        "operation": "START"
      }
    ]