我正在尝试使用dataweave以特定格式创建json。
xml在某些元素中有属性,我需要用它来在json文件中创建一个未定义的键。
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>
json输出应该如下所示。诀窍是,当Section = null时,应该使用Ungrouped,否则使用Section的值。
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"
}]
}
}
}
这是我的数据编织的开始。我没有进一步发展,因为我能够设置Ungrouped部分至关重要。
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
}
)}
}
}
我希望我已经涵盖了一切。如果我没有,请告诉我,因为这是我在stackoverflow上的第一篇文章。
答案 0 :(得分:0)
如果没有其他Ingredients
没有Section
,则可以执行以下操作:
%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)
}
}
)}