We need to convert the object to an Array of objects and do map on the field but the field is incremental like field1, field2 which is where we got stuck. I tried the below code:
output application/json
---
payload.main.field map(value) -> {
"name": value.name,
"age": value.age,
"location": value.location[0].country
}
Input:
{
"main": {
"field1": {
"name": "value",
"age": 20,
"address": {
"location": [
{
"country": "US",
"zipcode": 1234
},
{
"country": "US",
"zipcode": 1234
}
]
}
},
"field2": {
"name": "pqr",
"age": 23,
"address": {
"location": [
{
"country": "CA",
"zipcode": 1235
},
{
"country": "US",
"zipcode": 1234
}
]
}
},
"field3": {
"name": "abc",
"age": 22,
"address": {
"location": [
{
"country": "BU",
"zipcode": 1236
},
{
"country": "US",
"zipcode": 1234
}
]
}
}
}
}
For the above Input, Below is the expected response.
Expected Output:
{
"main": [
{
"name": "value",
"age": 20
"location": "US"
},
{
"name": "pqr",
"age": 23
"location": "CA"
},
{
"name": "abc",
"age": 22
"location": "BU"
}
]
}
For location, it will be like location[0].country when the array size is not 0 and country not null.
CodePudding user response:
output application/json
---
main : payload.main pluck $ map {
"name": $.name,
"age": $.age,
"location": if( sizeOf($.address.location) !=0) $.address.location[0].country else "N/A"
}
CodePudding user response:
%dw 2.0 output application/json
flatten(payload.main mapObject { "name" : $.name, "age" : $.age, "address" : flatten($.address pluck $ map( $ map valuesOf($))) reduce ($$ $) } pluck $)
=====================OR=============================
%dw 2.0 output application/json
flatten(flatten((payload pluck $) map { "a" : ($ pluck $) map ($ pluck $) }.a )reduce ((item, acc=[]) -> acc item ) map ( if(typeOf($)~="Object") ($ pluck ($ map {"" : $.country," " : $.zipcode}) ) reduce $ reduce ($$ $) pluck $ else $ ) )