0

我正在尝试使用 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 部分至关重要。

数据编织

%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 上的第一篇文章。

4

1 回答 1

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)
    }
  }
)}
于 2016-01-20T14:38:36.647 回答