Search code examples
dataweavemulesoftanypoint-studiomule4

How to dynamically set JSON field name in Mule 4


JSON received from API.

{
  "success": true,
  "timestamp": 1645988822,
  "base": "EUR",
  "date": "2022-02-27",
  "rates": {
    "AED": 4.140586,
    "AFN": 102.662987,
    "ALL": 121.380824,
    "AMD": 538.7856,
    "ANG": 2.016644,
    "AOA": 559.803561
  }
}

I am parsing JSON through this way in data weave expression but it gives error

%dw 2.0
output application/json
---
{
    "Result":
    {
        "Data":payload.rates.{Currency}        // Currency=AED  
    }
}

Desired JSON output should be as follow

{
    "Result":
    {
        "Data":4.140586
    }
}

Solution

  • You are using an incorrect syntax. payload.rates is an object so you can just use the dynamic selector:

    %dw 2.0
    output application/json
    var selectedCurrency="AED"
    ---
    {
        "Result":
        {
            "Data": payload.rates[selectedCurrency]
            
        }
    }
    

    Output:

    {
      "Result": {
        "Data": 4.140586
      }
    }