How to get the required json path? - json

I had this type of JSON structure and I want to fetch the upper element in the hierarchy on applying condition on lower element in hierarchy
{
"name": "ninja",
"contry": "India",
"Account": [
{
"id": "123",
"orgId": 223,
"investment": [
{
"invetmentId": "111",
"name": "India tech",
"performance": [
{
"id": "123",
"performanceSet": [
{
"amount": "210",
"currency": "YEN"
},
{
"amount": "231",
"currency": "USD"
},
{
"amount": "233",
"currency": "USD"
},
{
"amount": "250",
"currency": "IND"
}
],
"loyal": "250"
}
]
},
{
"invetmentId": "111",
"name": "USA tech",
"performance": [
{
"id": "245",
"performanceSet": [
{
"amount": "956",
"currency": "ASD"
},
{
"amount": "231",
"currency": "USD"
},
{
"amount": "233",
"currency": "USD"
},
{
"amount": "250",
"currency": "IND"
}
],
"loyal": "250"
}
]
}
]
}
]
}
So what I need is I need the investment name for which performance.id = 123 i.e it should return "India tech".So I want to know if that can be possible or not if yes how can I get that?

This method doesn't use nested forEach which is O(n²) and it stops iterating once it finds the matched result
data = { name: "ninja", contry: "India", Account: [ { id: "123", orgId: 223, investment: [ { invetmentId: "111", name: "India tech", performance: [ { id: "123", performanceSet: [ { amount: "210", currency: "YEN", }, { amount: "231", currency: "USD", }, { amount: "233", currency: "USD", }, { amount: "250", currency: "IND", }, ], loyal: "250", }, ], }, { invetmentId: "111", name: "USA tech", performance: [ { id: "245", performanceSet: [ { amount: "956", currency: "ASD", }, { amount: "231", currency: "USD", }, { amount: "233", currency: "USD", }, { amount: "250", currency: "IND", }, ], loyal: "250", }, ], }, ], }, ], };
res = [];
finfperf = (id) => {
data.Account.forEach((inv) =>
res.push(
inv.investment.find((o) => o.performance.some((a) => a.id == id)).name
)
);
return res;
};
console.log(finfperf(123));
console.log(finfperf(245));

Related

MongoDb Add field in array only is the arry is not null

Now I have a new situation Version 3.0.
I have this fake json:
[
{
"type":"PF",
"code":12345,
"Name":"Darth Vader",
"currency":"BRL",
"status":"ACTIVE",
"localization":"NABOO",
"createDate":1627990848665,
"olderAdress":[
{
"localization":"DEATH STAR",
"status":"BLOCKED",
"createDate":1627990848665
},
{
"localization":"TATOOINE",
"status":"CANCELLED",
"createDate":1627990555665
},
{
"localization":"ALDERAAN",
"status":"INACTIVED",
"createDate":1627990555665
}
]
},
{
"type":"PF",
"code":12345,
"Name":"Anakin Skywalker",
"currency":"BRL",
"status":"ACTIVE",
"localization":"NABOO",
"createDate":1627990848665,
"olderAdress":null
}
]
And I need to add a new field in each array element ONLY IF THE ARRAY IS NOT NULL. But I need to do that by aggregate because I'm using this result in Spring before sending to the users.
I need this result:
[
{
"type": "PF",
"code": 12345,
"Name": "Darth Vader",
"currency": "BRL",
"status": "ACTIVE",
"localization": "NABOO",
"createDate": 1627990848665,
"olderAddress": [
{
"localization": "DEATH STAR",
"status": "BLOCKED",
"createDate": 1627990848665,
"isItemOfOlderAddress" : true
},
{
"localization": "TATOOINE",
"status": "CANCELLED",
"createDate": 1627990555665,
"isItemOfOlderAddress" : true
},
{
"localization": "ALDERAAN",
"status": "INACTIVED",
"createDate": 1627990555665,
"isItemOfOlderAddress" : true
},
]
},
{
"type": "PF",
"code": 12345,
"Name": "Anakin Skywalker",
"currency": "BRL",
"status": "ACTIVE",
"localization": "NABOO",
"createDate": 1627990848665,
"olderAdress": null
},
]
So I added the field isItemOfOlderAddress only where olderAddress is not null and where olderAddress is null I only show the default information. How can I do that?
Query
if olderAdress is an array(so not null also), add "isItemOfOlderAddress": true field to all members
else keep the old value(so keep the null also)
Test code here
db.collection.aggregate([
{
"$set": {
"olderAdress": {
"$cond": [
{
"$isArray": [
"$olderAdress"
]
},
{
"$map": {
"input": "$olderAdress",
"in": {
"$mergeObjects": [
"$$this",
{
"isItemOfOlderAddress": true
}
]
}
}
},
"$olderAdress"
]
}
}
}
])

How to exclude specific fields from JSON using groovy

I would like to exclude the items which don't have productModel property in the below JSON. How can we achieve this in groovy
I tried using hasProperty but not worked for me as expected. If possible can I get some sample snippet
I tried below code - but didn't work as I expected.
response.getAt('myData').getAt('data').getAt('product').hasProperty('productModel').each { println "result ${it}" }
Any help would be really appreciated.
{
"myData": [{
"data": {
"product": {
"productId": "apple",
"productName": "iPhone",
"productModel": "6s"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {}
},
{
"data": {
"product": {
"productId": "apple",
"productName": "iPhone",
"productModel": "7"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {}
},
{
"data": {
"product": {
"productId": "apple",
"productName": "Macbook"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {}
}
],
"metadata": {
"count": 3,
"offset": 0
}
}
If you want to exclude specific fields from JSON object then you have to recreate it using filtered data. The crucial part takes these two lines (assuming that json variable in the below example stores your JSON as text):
def root = new JsonSlurper().parseText(json)
def myData = root.myData.findAll { it.data.product.containsKey('productModel') }
What happens here is we access root.myData list and we filter it using findAll(predicate) method and predicate in this case says that only objects that have key productModel in path data.product are accepted. This findAll() method does not mutate existing list and that is why we store the result in variable myData - after running this method we will end up with a list of size 2.
In next step you have to recreate the object you want to represent as a JSON:
def newJsonObject = [
myData: myData,
metadata: [
count: myData.size(),
offset: 0
]
]
println JsonOutput.prettyPrint(JsonOutput.toJson(newJsonObject))
In this part we create newJsonObject and in the end we convert it to a JSON representation.
Here is the full example:
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
def json = '''{
"myData": [{
"data": {
"product": {
"productId": "apple",
"productName": "iPhone",
"productModel": "6s"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {}
},
{
"data": {
"product": {
"productId": "apple",
"productName": "iPhone",
"productModel": "7"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {}
},
{
"data": {
"product": {
"productId": "apple",
"productName": "Macbook"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {}
}
],
"metadata": {
"count": 3,
"offset": 0
}
}'''
def root = new JsonSlurper().parseText(json)
def myData = root.myData.findAll { it.data.product.containsKey('productModel') }
def newJsonObject = [
myData: myData,
metadata: [
count: myData.size(),
offset: 0
]
]
println JsonOutput.prettyPrint(JsonOutput.toJson(newJsonObject))
And here is the output it produces:
{
"myData": [
{
"data": {
"product": {
"productId": "apple",
"productName": "iPhone",
"productModel": "6s"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [
{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {
}
},
{
"data": {
"product": {
"productId": "apple",
"productName": "iPhone",
"productModel": "7"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [
{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {
}
}
],
"metadata": {
"count": 2,
"offset": 0
}
}

Re-arrange JSON file (using adjacency matrix)

I have a json file that looks like this:
[
{
"id": 1,
"country": "Greece",
"names": [
"Alex",
"Betty",
"Catherine",
"Dave",
"Edward",
"Frank",
"George",
"Helen",
"Irene"
]
},
{
"id": 2,
"country": "US",
"names": [
"John",
"Alex",
"Edward",
"Kate",
"Robert",
"Irene",
"Tim",
"Sam"
]
},
{
"id": 3,
"country": "France",
"names": [
"Helen",
"Kate",
"Louise",
"Tim",
"Catherine",
"Arthur",
"Frank",
"Natalie",
"Dave"
]
},
{
"id": 4,
"country": "India",
"names": [
"Ritesh",
"Alex",
"Betty",
"Robert"
]
},
{
"id": 5,
"country": "India",
"names": [
"Nafeez",
"Tom",
"Natalie",
"Gunar",
"Louise",
"Arthur"
]
}
]
I want it to be "name centered" and look like this:
{
"groups": [
{
"gr_id":1
"name":"Alex",
"country":"Greece"
},
.........
{
"gr_id":1
"name":"Irene",
"country":"Greece"
},
{
"gr_id":2
"name":"John",
"country":"US"
..........
{
"gr_id":2
"name":"Sam",
"country":"US"
},
{
"gr_id":3
"name":"Helen",
"country":"France"
},
.........
{
"gr_id":3
"name":"Dave",
"country":"France"
},
{
"gr_id":4
"name":"Ritesh",
"country":"India"
},
........
{
"gr_id":4
"name":"Robert",
"country":"India"
},
{
"gr_id":5
"name":"Nafeez",
"country":"India"
},
...........
{
"gr_id":5
"name":"Arthur",
"country":"India"
}
],
"links": [
{
"source":"Alex"
"target":"Irene",
"count":1
"country":"Greece"
},
...
{
"source":"Alex"
"target":"Arthur",
"count":0
"country":"India"
},
...
]
}
For count in Links I have an adjacency matrix for each country/name (csv format) like this :screenshot of csv file (ad. matrix for India)
This json is just an example. I have much bigger file (I need it for D3 graph visualization)
Reduce() and map() work perfectly for this. This basically takes each item and then maps over the names, appending the results of map() to an array:
let obj = {}
obj.groups = json.reduce(
(acc, curr) => acc.concat(curr.names.map(
item => ({gr_id: curr.id, country: curr.country, name: item})
)), [])
console.log(obj)
// { groups:
// [ { gr_id: 1, country: 'Greece', name: 'Alex' },
// { gr_id: 1, country: 'Greece', name: 'Betty' },
// ...etc
// ]
// }

Unmarshal deeply nested json in golang

I have an ugly way of unmarshalling the following json, but it requires much manual work. I am looking for a more programmatic way to obtain the various team names, if I didn't know how many teams exactly there were originally. It's truly one of the most poorly structured api's I've come across.
data := []byte(`{
"fantasy_content": {
"copyright": "Data provided by Yahoo! and STATS, LLC",
"league": [
{
"allow_add_to_dl_extra_pos": 0,
"current_week": "1",
"draft_status": "predraft",
"edit_key": "1",
"end_date": "2017-12-25",
"end_week": "16",
"game_code": "nfl",
"is_cash_league": "0",
"is_pro_league": "0",
"league_id": "XXXXX",
"league_key": "XXXX",
"league_type": "private",
"league_update_timestamp": null,
"name": "XXXXXX",
"num_teams": 14,
"renew": "XXXX",
"renewed": "",
"scoring_type": "head",
"season": "2017",
"short_invitation_url": "XXXXX",
"start_date": "2017-09-07",
"start_week": "1",
"url": "XXXXXX",
"weekly_deadline": ""
},
{
"teams": {
"0": {
"team": [
[
{
"team_key": "XXXX"
},
{
"team_id": "1"
},
{
"name": "XXXXX"
},
[],
{
"url": "XXXXX"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"XXX"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXXXX",
"guid": "XX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"is_commissioner": "1",
"manager_id": "1",
"nickname": "Andrew"
}
}
]
}
]
]
},
"1": {
"team": [
[
{
"team_key": "XXXXX"
},
{
"team_id": "2"
},
{
"name": "XXXXX"
},
[],
{
"url": "XXXXX"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "XXXX"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXXX#yahoo.com",
"guid": "XXXX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"manager_id": "2",
"nickname": "Andrew"
}
},
{
"manager": {
"email": "XXX#yahoo.com",
"guid": "XX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"is_comanager": "1",
"manager_id": "15",
"nickname": "XX"
}
}
]
}
]
]
},
"10": {
"team": [
[
{
"team_key": "XXX"
},
{
"team_id": "11"
},
{
"name": "XXX"
},
[],
{
"url": "https://football.fantasysports.yahoo.com/f1/XXX"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "https://s.yimg.com/dh/ap/fantasy/nfl/img/icon_01_100.png"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXX#gmail.com",
"guid": "XX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"manager_id": "11",
"nickname": "XX"
}
}
]
}
]
]
},
"2": {
"team": [
[
{
"team_key": "371.l.102542.t.3"
},
{
"team_id": "3"
},
{
"name": "XXX"
},
[],
{
"url": "https://football.fantasysports.yahoo.com/f1/XX/3"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "https://ct.yimg.com/cy/5603/30147468023_1c705edb29_192sq.jpg?ct=fantasy"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXXgmail.com",
"guid": "XXXX",
"image_url": "https://s.yimg.com/wv/images/6c93ed606f742d4c075bc091633cc072_64.jpg",
"manager_id": "3",
"nickname": "XX"
}
}
]
}
]
]
},
"3": {
"team": [
[
{
"team_key": "371.l.102542.t.4"
},
{
"team_id": "4"
},
{
"name": "XX"
},
[],
{
"url": "https://football.fantasysports.yahoo.com/f1/XX/4"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "https://s.yimg.com/dh/ap/fantasy/nfl/img/icon_10_100.png"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXX#yahoo.com",
"guid": "XX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"manager_id": "4",
"nickname": "XX"
}
}
]
}
]
]
},
"8": {
"team": [
[
{
"team_key": "XXX"
},
{
"team_id": "9"
},
{
"name": "XxX"
},
[],
{
"url": "https://football.fantasysports.yahoo.com/f1/XX/9"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "https://ct.yimg.com/cy/8393/28682944304_33bda49603_192sq.jpg?ct=fantasy"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXX",
"guid": "XXX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"manager_id": "9",
"nickname": "XXX"
}
}
]
}
]
]
},
"count": 14
}
}
],
"refresh_rate": "60",
"time": "110.55207252502ms",
"xml:lang": "en-US",
"yahoo:uri": "/fantasy/v2/league/XXXX/teams"
}
}`)
The following works, but it's a hassle and I have to hard code the different struct values per team, to get data for that team.
type TeamApi_ struct {
TeamKey string `json:"team_key"`
TeamId string `json:"team_id"`
Name string `json:"name"`
}
type LeaguesApi struct {
NumTeams int `json:"num_teams"`
TeamsApi struct {
Zero struct {
TeamsApi_ [][]TeamApi_ `json:"team"`
} `json:"0"`
One struct {
TeamsApi_ [][]TeamApi_ `json:"team"`
} `json:"1"`
Two struct {
TeamsApi_ [][]TeamApi_ `json:"team"`
} `json:"2"`
Three struct {
TeamsApi_ [][]TeamApi_ `json:"team"`
} `json:"3"`
} `json:"teams"`
}
type LeagueApiResult struct {
FantasyContent struct {
LeagueApi []LeaguesApi `json:"league"`
} `json:"fantasy_content"`
}
var Result LeagueApiResult
err := json.Unmarshal(data, &Result)
if err != nil {
fmt.Println(err)
}
fmt.Println(Result.FantasyContent.LeagueApi[1].TeamsApi.One.TeamsApi_[0][2].Name)
You probably want to use a custom JSON unmarshaller for this. You can see an example of how to use one here: http://choly.ca/post/go-json-marshalling/
Since the data is structured the way it is, with the teams section both containing teams and the count field, you'll likely need a fair bit of manual logic in there.
First, you can start by defining the League:
type League struct {
AllowAddToDlExtraPos int `json:"allow_add_to_dl_extra_pos,omitempty"`
CurrentWeek string `json:"current_week,omitempty"`
DraftStatus string `json:"draft_status,omitempty"`
EditKey string `json:"edit_key,omitempty"`
EndDate string `json:"end_date,omitempty"`
EndWeek string `json:"end_week,omitempty"`
GameCode string `json:"game_code,omitempty"`
IsCashLeague string `json:"is_cash_league,omitempty"`
IsProLeague string `json:"is_pro_league,omitempty"`
LeagueID string `json:"league_id,omitempty"`
LeagueKey string `json:"league_key,omitempty"`
LeagueType string `json:"league_type,omitempty"`
LeagueUpdateTimestamp interface{} `json:"league_update_timestamp,omitempty"`
Name string `json:"name,omitempty"`
NumTeams int `json:"num_teams,omitempty"`
Renew string `json:"renew,omitempty"`
Renewed string `json:"renewed,omitempty"`
ScoringType string `json:"scoring_type,omitempty"`
Season string `json:"season,omitempty"`
ShortInvitationURL string `json:"short_invitation_url,omitempty"`
StartDate string `json:"start_date,omitempty"`
StartWeek string `json:"start_week,omitempty"`
URL string `json:"url,omitempty"`
WeeklyDeadline string `json:"weekly_deadline,omitempty"`
Teams []Team `json:"-"`
}
Next, we can define the Team structure the way we want it to look.
type Team struct {
// Declare the fields of a Team
}
And finally, we declare a custom unmarshal function for the League.
func (l *League) UnmarshalJSON(data []byte) error {
type Alias League
aux := &struct {
*Alias
Teams map[string]interface{} `json:"teams"`
}{
Alias: (*Alias)(l),
}
if err := json.Unmarshal(data, aux); err != nil {
return err
}
var teams []Team
for num, team := range aux.Teams {
// Add your code to parse each of the teams from the
// map you declared above.
}
l.Teams = teams
return nil
}
The unmarshal function will be called by Golangs json library automatically when it hits the League structure inside the LeagueApiResult.

Aggregate two payloads in Mule ESB

My mule code is hitting two tables and getting some details.
First one is order details, which I am storing in a flow variable i.e order and another database is returning order item details which I am storing in orderitem variable.
I want to aggregate both the payload based on one condition. Every orderId has order items (which is stored in flowVars.orderitem) and map these order items to respective orderID.
flowVars.order value is as below
[{partnerId=e83185e9f33e4234ba9eaa81dba515ad, orderId=12345, orderDate=2017-02-28 16:41:41.0, id=22}, {partnerId=e83185e9f33e4234ba9eaa81dba515ad, orderId=123456, orderDate=2017-02-28 16:41:41.0, id=23}, {partnerId=e83185e9f33e4234ba9eaa81dba515ad, orderId=11111, orderDate=2017-02-28 16:41:41.0, id=24}, {partnerId=e83185e9f33e4234ba9eaa81dba515ad, orderId=321123, orderDate=2017-05-19 15:25:41.0, id=26}]
and flowVars.orderitem value is as below
[{productCode=ELT-LP-ICND1-020067, orderId=12345, quantity=10, id=14}, {productCode=ELT-IP-ICND1-1.0, orderId=12345, quantity=11, id=15}, {productCode=ELT-LP-ICND1-020067, orderId=123456, quantity=12, id=16}, {productCode=ELT-IP-ICND1-1.0, orderId=123456, quantity=13, id=17}, {productCode=ELT-LP-ICND1-020067, orderId=11111, quantity=14, id=18}, {productCode=ELT-IP-ICND1-1.0, orderId=11111, quantity=15, id=19}, {productCode=ELT-LP-ICND2-020067, orderId=321123, quantity=5, id=20}]
Expected Output
[
{
"orderId": "12345",
"orderDate": "2017-02-28T16:41:41",
"partnerId": "e83185e9f33e4234ba9eaa81dba515ad",
"orderItems": [
{
"productCode": "ELT-LP-ICND1-020067",
"quantity": "10"
},
{
"productCode": "ELT-IP-ICND1-1.0",
"quantity": "11"
}
]
},
{
"orderId": "123456",
"orderDate": "2017-02-28T16:41:41",
"partnerId": "e83185e9f33e4234ba9eaa81dba515ad",
"orderItems": [
{
"productCode": "ELT-LP-ICND1-020067",
"quantity": "12"
},
{
"productCode": "ELT-IP-ICND1-1.0",
"quantity": "13"
}
]
},
{
"orderId": "11111",
"orderDate": "2017-02-28T16:41:41",
"partnerId": "e83185e9f33e4234ba9eaa81dba515ad",
"orderItems": [
{
"productCode": "ELT-LP-ICND1-020067",
"quantity": "14"
},
{
"productCode": "ELT-IP-ICND1-1.0",
"quantity": "15"
}
]
},
{
"orderId": "321123",
"orderDate": "2017-05-19T15:25:41",
"partnerId": "e83185e9f33e4234ba9eaa81dba515ad",
"orderItems": [
{
"productCode": "ELT-LP-ICND1-020067",
"quantity": "5"
}
]
}
]
Here I need to show respective order item details of an order. So basically I need to combine both the payloads.
I tried using dataweave but not luck.
Dataweave code:
%dw 1.0
%output application/json
%var mergeddata = flowVars.orderitem groupBy $.orderId
---
flowVars.order map ((data,index) ->
{
orderid: data.orderId,
partnerid: data.partnerId,
orderdate: data.orderDate,
order: flowVars.orderitem default [] map ((data1 ,indexOf) ->
{
(productcode: data1.productCode) when (data1.orderId == data.orderId),
(quantity: data1.quantity) when (data1.orderId == data.orderId) ,
(id: data1.id) when (data1.orderId == data.orderId)
}
)})
And output after transformation:
{
"orderid": "12345",
"partnerid": "e83185e9f33e4234ba9eaa81dba515ad",
"orderdate": "2017-02-28T16:41:41",
"order": [
{
"productcode": "ELT-LP-ICND1-020067",
"quantity": 10,
"id": 14
},
{
"productcode": "ELT-IP-ICND1-1.0",
"quantity": 11,
"id": 15
},
{
},
{
},
{
},
{
},
{
}
]
},
{
"orderid": "123456",
"partnerid": "e83185e9f33e4234ba9eaa81dba515ad",
"orderdate": "2017-02-28T16:41:41",
"order": [
{
},
{
},
{
"productcode": "ELT-LP-ICND1-020067",
"quantity": 12,
"id": 16
},
{
"productcode": "ELT-IP-ICND1-1.0",
"quantity": 13,
"id": 17
},
{
},
{
},
{
}
]
},
{
"orderid": "11111",
"partnerid": "e83185e9f33e4234ba9eaa81dba515ad",
"orderdate": "2017-02-28T16:41:41",
"order": [
{
},
{
},
{
},
{
},
{
"productcode": "ELT-LP-ICND1-020067",
"quantity": 14,
"id": 18
},
{
"productcode": "ELT-IP-ICND1-1.0",
"quantity": 15,
"id": 19
},
{
}
]
},
{
"orderid": "321123",
"partnerid": "e83185e9f33e4234ba9eaa81dba515ad",
"orderdate": "2017-05-19T15:25:41",
"order": [
{
},
{
},
{
},
{
},
{
},
{
},
{
"productcode": "ELT-LP-ICND2-020067",
"quantity": 5,
"id": 20
}
]
}
]
As you can see that I am almost there and able to map order item details with respective orderId but still I am getting some blank values after transformation.
Can anyone help me to achieve expected output. Thanks in advance!!!
You need to filter the flowVars.orderitem map, rather than iterate it in full and only print values when the orderId matches.
order: ((flowVars.orderitem default []) filter (data.orderId == $.orderId)) map ((data1 ,indexOf) -> {
productcode: data1.productCode,
quantity: data1.quantity
id: data1.id
})
You can then remove all of those 'when' statements too.