Uday
Uday

Reputation: 19

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

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.

Upvotes: 0

Views: 182

Answers (2)

StackOverflowed
StackOverflowed

Reputation: 759

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

Upvotes: 0

Anurag Sharma
Anurag Sharma

Reputation: 935

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

Upvotes: 1

Related Questions