JSON キーの名前変更

この DataWeave の例では、JSON オブジェクトの一部のキーの名前を変更し、出力の他のキーの名前はすべてそのままにします。

次の関数を使用します。

  • JSON オブジェクトの key:value ペアを調べる mapObject

  • どのような場合にキーの名前を変更するのかを単独で決定する if

  • 新しい名前の 2 つのキーを除くすべてのキーの名前を保持する ifand

  • キーの型を String (文字列) に強制変換する as

DataWeave
%dw 2.0
output application/json
---
payload.flights map (flight) -> {
    (flight mapObject (value, key) -> {
        (emptySeats: value) if(key as String == 'availableSeats'),
        (airline: value) if(key as String == 'airlineName'),
        ((key):value) if(key as String !='availableSeats' and key as String != 'airlineName')
    })
}
入力
{
  "flights":[
  {
  "availableSeats":45,
  "airlineName":"Ryan Air",
  "aircraftBrand":"Boeing",
  "aircraftType":"737",
  "departureDate":"12/14/2017",
  "origin":"BCN",
  "destination":"FCO"
  },
  {
  "availableSeats":15,
  "airlineName":"Ryan Air",
  "aircraftBrand":"Boeing",
  "aircraftType":"747",
  "departureDate":"08/03/2017",
  "origin":"FCO",
  "destination":"DFW"
  }]
}
出力
[
  {
    "emptySeats": 45,
    "airline": "Ryan Air",
    "aircraftBrand": "Boeing",
    "aircraftType": "737",
    "departureDate": "12/14/2017",
    "origin": "BCN",
    "destination": "FCO"
  },
  {
    "emptySeats": 15,
    "airline": "Ryan Air",
    "aircraftBrand": "Boeing",
    "aircraftType": "747",
    "departureDate": "08/03/2017",
    "origin": "FCO",
    "destination": "DFW"
  }
]

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub