Home > Mobile >  How to split a string from an object in an array into new objects in the array
How to split a string from an object in an array into new objects in the array

Time:06-17

We have the below input which has an address field with colon as value. This need to be considered as a new object. Input:

{
 "Customer" : [
  {
   "name": "abc",
   "age": 23,
   "address": "test4"
  },
  {
   "name": "xyz",
   "age": 28,
   "address": "test:mule"
  },
  {
   "name": "pqr",
   "age": 25,
   "address": "test1"
  }
 ]
}

Expected Output considering colon in field:

{
 "Customer" : [
  {
   "name": "abc",
   "age": 23,
   "address": "test4"
  },
  {
   "name": "xyz",
   "age": 28,
   "address": "test"
  },
 {
   "name": "xyz",
   "age": 28,
   "address": "mule"
  },
  {
   "name": "pqr",
   "age": 25,
   "address": "test1"
  }
 ]
}

If we have colon in the field address then that needs to be updated as a different object.

CodePudding user response:

you can try the below DataWeave Script

%dw 2.0
output application/json  
---
 Customer: payload.Customer flatMap ((item, index) -> do {
      var codes = item.address splitBy ":"
      ---
      codes map {
        "name": item.name,
        "age": item.age,
        "address": $
      }
    })

below is the screenshot with input, script, and required output enter image description here

CodePudding user response:

%dw 2.0
output application/json
---
Customer: flatten(payload.Customer map (
     ($.address splitBy ":") map (item,index) -> ($ - "address"    {address: item })
 
))
  • Related