bazaarvoice / jolt

JSON to JSON transformation library written in Java.
Apache License 2.0
1.54k stars 328 forks source link

Map objects from two arrays by object key. #1198

Open FlorinCiocirlan opened 1 year ago

FlorinCiocirlan commented 1 year ago

Hi There,

I'm struggling to transform this json input `

{ "RoomFacilities": [ { "RoomName": "Deluxe Double Room", "RoomFacility": "Daily housekeeping" }, { "RoomName": "Deluxe Twin Room", "RoomFacility": "Iron/ironing board" }, { "RoomName": "Deluxe Twin Room", "RoomFacility": "Heating" }, { "RoomName": "Deluxe Double Room", "RoomFacility": "Ceiling fan" } ], "Rooms": [ { "Name": "Deluxe Twin Room" }, { "Name": "Deluxe Double Room" } ] }

to this output:

"Rooms": [ { "Name": "Deluxe Twin Room", "Facilities": [{ "Name": "Iron/ironing board", "Name": "Heating", }], }, { "Name": "Deluxe Double Room", "Facilities": [{ "Name": "Ceiling fan", "Name": "Daily housekeeping", }] } ]

Basically i want to iterate over RoomsFacilities and get the corresponding Room from Rooms by Rooms.name = RoomFacilities.RoomName and then put every facility that's matching the room name under room object in facilities array.

DId anyone here have to do this before ? I mean i've tried using chat-gpt and also tried myself with no results.

AndrewKZY commented 1 year ago

{ "Rooms": [{ "Name": "Deluxe Twin Room", "Facilities": ["Iron/ironing board", "Heating"] }, { "Name": "Deluxe Double Room", "Facilities": ["Ceiling fan", "Daily housekeeping"] } ] }

This should be your expected output? The one above does not seem to be a valid JSON output

My output so far from my current spec { "Rooms" : [ { "Name" : "Deluxe Twin Room", "Facilities" : [ "Daily housekeeping", "Iron/ironing board", "Heating", "Ceiling fan" ] }, { "Name" : "Deluxe Double Room" } ] }

Spec [ { "operation": "shift", "spec": { "Rooms": { "*": { "Name": "Rooms[&1].Name" } }, "RoomFacilities": { "*": { "RoomName": { "*": { "@(2,RoomFacility)": "Rooms[#2].Facilities[]" } } } } } } ]

DhruvSingh861 commented 1 year ago

Hello @FlorinCiocirlan

I think this is what you want in output :-

{
  "Rooms" : [ {
    "Facilities" : [ "Iron/ironing board", "Heating" ],
    "Name" : "Deluxe Twin Room"
  }, {
    "Facilities" : [ "Daily housekeeping", "Ceiling fan" ],
    "Name" : "Deluxe Double Room"
  } ]
}

spec for this :-

[
  {
    "operation": "shift",
    "spec": {
      "RoomFacilities": {
        "*": {
          "@(0,RoomFacility)": "@(0,RoomName)"
        }
      },
      "*": "&"
    }
  }
,
  {
    "operation": "shift",
    "spec": {
      "Rooms": {
        "*": {
          "*": "Rooms[#2].&",
          "@(0,Name)": {
            "*": {
              "@(4,&)": "Rooms[#4].Facilities"
            }
          }
        }
      }
    }
  }
]