Search code examples
mulemule-studiodataweavemule-esbmulesoft

Where to use curly brace and open brace in data weave


I have an input like this to data weave code

[
  {
    "CountryCode": "????",
    "District": "????",
    "ID": 1,
    "Name": "????",
    "Population": 1
  },
  {
    "CountryCode": "????",
    "District": "????",
    "ID": 200,
    "Name": "????",
    "Population": 1000
  }
]

and the data weave code is

%dw 1.0
%output application/xml
---

    WorldDetails: {
        (payload map ((payload01 , indexOfPayload01) -> {
            EachDetail: {
                countrycode: payload01.CountryCode,
                district: payload01.District,
                id: payload01.ID,
                Name: payload01.Name,
                population: payload01.Population
            }
        }))
    }

here is resultant output

 <?xml version='1.0' encoding='UTF-8'?>
<WorldDetails>
  <EachDetail>
    <countrycode>????</countrycode>
    <district>????</district>
    <id>1</id>
    <Name>????</Name>
    <population>1</population>
  </EachDetail>
  <EachDetail>
    <countrycode>????</countrycode>
    <district>????</district>
    <id>200</id>
    <Name>????</Name>
    <population>1000</population>
  </EachDetail>
</WorldDetails>

we can see curly braces and open braces in code. I have lot of confusion exactly where to use these two kinds of braces in the code. can any one explain in the code why they used particular kind braces at particular line of code. simply want to know where to use open braces and closed braces in data weave code.


Solution

  • Cleaning it up a little bit:

    %dw 1.0
    %output application/xml
    ---
    WorldDetails: {
        (payload map {
            EachDetail: {
                countrycode: $.CountryCode,
                district: $.District,
                id: $.ID,
                Name: $.Name,
                population: $.Population
            }
        })
    }
    

    They way I think of it:

    Parentheses () are used to evaluate an expression, pass arguments to functions, or change order of operation.

    Brackets {} are used for defining objects.

    If you remove the parentheses, it looks like this:

    WorldDetails: payload map {
        EachDetail: {
            countrycode: $.CountryCode,
            district: $.District,
            id: $.ID,
            Name: $.Name,
            population: $.Population
        }
    }
    

    You'll get an error Cannot coerce a :array to a :object because your map is returning an array, not an object. So you evaluate the map, and force it into an object with {}. If you want your map to return an array on purpose, you can use payload map ().

    I'm sure there will be a better answer, and then I can delete my post. This is the way I understand them though.