【问题标题】:Dataweave XML to JSON creating key pair value based on attribute in xmlDataweave XML to JSON 基于 xml 中的属性创建密钥对值
【发布时间】:2016-01-20 22:38:36
【问题描述】:

我正在尝试使用 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 上的第一篇文章。

【问题讨论】:

  • 所以困难的部分是将所有没有部分的成分分组,对吗?你能有更多没有部分的成分标签吗?

标签: mule dataweave


【解决方案1】:

如果没有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)
    }
  }
)}

【讨论】:

  • 非常简单的解决方案,我对 dataweave 的强大功能有了更多了解。谢谢肖基
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多