0
votes

I am trying to use dataweave to create a json in a particular format.

The xml has attributes in some of the elements and I need to use this to to create a undefined key in the json file.

XML

<Ingredients>
<Ingredient>225g/8oz unsalted butter, softened, plus extra for greasing</Ingredient>
<Ingredient>175g/6oz dried cranberries</Ingredient>
</Ingredients>
<Ingredients Section="FOR THE FRUIT">
<Ingredient>150ml/¼pt cloudy apple juice</Ingredient>
<Ingredient>50g/2oz unsalted butter</Ingredient>
</Ingredients>
<Ingredients Section="TO FEED THE CAKE (each time)">
<Ingredient>2 tbsp dark rum</Ingredient>
<Ingredient>1 tbsp maple syrup</Ingredient>
</Ingredients>

The json output should look like this. The trick is that when Section = null then Ungrouped should be used otherwise the value for Section is used.

JSON

 {
    "ingredients": {
        "Ungrouped": {
            "position": 0,
            "list": [{
                "position": 1,
                "description": "225g/8oz unsalted butter, softened, plus extra for greasing"
            }, {
                "position": 2,
                "description": "225g/8oz light muscovado sugar"
            }]
        },
        "FOR THE FRUIT": {
            "position": 1,
            "list": [{
                "position": 1,
                "description": "150ml/¼pt cloudy apple juice"
            }, {
                "position": 2,
                "description": "50g/2oz unsalted butter"
            }]
        },
        "TO FEED THE CAKE (each time)":{
            "position":2,
            "list": [{
                "position": 1,
                "description": "2 tbsp dark rum"
            },
            {
                "position": 2,
                "description": "1 tbsp maple syrup"
            }]
        }
    }
}

Here is the start of my data weave. I haven’t progressed further than this as it is crucial that i am able to set the Ungrouped section.

Dataweave

%dw 1.0
%input payload application/xml
%output application/json
---
{
recipe: {
"ingredients": { (payload.Recipe.*Ingredients.@Section map
'Ungrouped':{
  position : $$+0
    } when $ == null otherwise

'$':{
  position : $$+0
    }
)}
}
}

I hope I have covered everything. Please let me know if I haven’t as this is my first post on stackoverflow.

1
So the difficult part is grouping all the Ingredients that have no Section, right? Can you have more Ingredients tags without section?Shoki

1 Answers

0
votes

If there are no other Ingredients without Section, then you can do:

%dw 1.0
%output application/json
%var addPosition = (list) -> list map {
  "position": $$+1,
  "description" : $
}
---
recipe: ingredients: {(
  ("Ungrouped" + payload.Recipe.*Ingredients.@Section) map {
    "$" : {
      "position": $$,
      "list": addPosition(payload.Recipe.*Ingredients[$$].*Ingredient)
    }
  }
)}