Tony
Tony

Reputation: 2774

Using the DataWeave update operator, how can I target a nested node with a dynamic reference?

I'm trying to use the DataWeave update operator to either modify or delete a nested node in a JSON payload. The node's path will be passed dynamically and will change, so it can't be hardcoded.

The example in the MuleSoft documentation shows how to accomplish this with a simple payload:

Input:

{
  "name": "Ken",
  "lastName":"Shokida"
}

DataWeave:

%dw 2.0
var theFieldName = "name"
output application/json
---
payload update {
  case s at ."$(theFieldName)" -> "Shoki"
}

Output:

{
  "name": "Shoki",
  "lastName": "Shokida"
}

When I try to build anything at a deeper level using multiple dots, the expression does not resolve properly to the nested element.

Input :

{
  "person" : {
    "name" : "Joe Blow",
    "contact" : {
      "email" : "[email protected]",
      "phone" : {
        "cell" : {
          "personal" : "404-555-1234",
          "work" : "404-555-2345"
        }         
      }
    }
  }
}

Dataweave:

%dw 2.0
var node = "person.contact.phone.cell.work"
output application/json
---
payload update {
  case s at ."$(node)" -> "404-555-3456"
}

I've also tried variations of dynamic selection without using a nested dot structure ( "person['contact']['phone']['cell']['work']" ), but that wasn't successful either.

How can I accomplish this dynamically if I need to go deeper than top level into an object?

Upvotes: 1

Views: 58

Answers (1)

Harshank Bansal
Harshank Bansal

Reputation: 3315

The update operator does not support it. For more complex updates, you can use the update function from dw::util::Values which supports the path to be passed as an array for nested updates. (reference)

%dw 2.0
import update from dw::util::Values
var node = "person.contact.phone.cell.work" splitBy '.' //make it in array
output application/json
---
payload update node with "XXX"

enter image description here

I have tried to use array similarly with the update operator, but it does not work. You need to use the function version of it.

Upvotes: 2

Related Questions