csv到json的转换,其中某些标签可能不会随机出现

时间:2019-05-21 06:47:14

标签: mule dataweave mule-esb mulesoft

我有一个csv输入,如下所示:请注意,对于第二组值,标签Edible不再出现。还要注意,一个对象的数据分为列和三行:

Key|Value|ConcatenatedString
Name|Fruit|"apple,orange,pineapple"
Status|Good|"apple,orange,pineapple"
Edible|Yes|"apple,orange,pineapple"
Name|Furniture|"chair,table,bed"
Status|Good|"chair,table,bed"

我需要以下json格式:

{
Name:"Fruit",
Status:"Good",
Edible:"Yes"
ConcatenatedString:"apple,orange,pineapple"
},
{
Name:"Furniture",
Status:"Good",
Edible:null
ConcatenatedString:"chair,table,bed"
}

当所有对象的所有标签都出现时,我正在使用以下代码。但是现在有些标签可能根本没有了,我不确定如何处理这个问题,就像我使用基于位置的方法一样:

%dw 2.0

input payload application/csv separator='|'
output application/json
---
payload map
{
Name:payload[(($$)*4)+0].Value,
Status:payload[(($$)*4)+1].Value,
Edible:payload[(($$)*4)+2].Value,
ConcatenatedString:payload[(($$)*4)+0]."ConcatenatedString"
} 
filter ($.Name!= null)

预先感谢

Anoop

1 个答案:

答案 0 :(得分:0)

这是我的答案。

%dw 2.0
input payload application/csv  separator="|"
output application/json  
---
payload 
    groupBy ((item, index) -> item.ConcatenatedString) 
    pluck ((value, key, index) -> {
        Name: (value filter ((item, index) -> item.Key == "Name")).Value[0],
        Status: (value filter ((item, index) -> item.Key == "Status")).Value[0],
        Edible: (value filter ((item, index) -> item.Key == "Edible")).Value[0],
        ConcatenatedString: key
    })

基本上,首先需要按要分组的条件进行分组。就您而言,ConcatenatedString。这将返回

{
  "chair,table,bed": [
    {
      "Key": "Name",
      "Value": "Furniture",
      "ConcatenatedString": "chair,table,bed"
    },
    {
      "Key": "Status",
      "Value": "Good",
      "ConcatenatedString": "chair,table,bed"
    }
  ],
  "apple,orange,pineapple": [
    {
      "Key": "Name",
      "Value": "Fruit",
      "ConcatenatedString": "apple,orange,pineapple"
    },
    {
      "Key": "Status",
      "Value": "Good",
      "ConcatenatedString": "apple,orange,pineapple"
    },
    {
      "Key": "Edible",
      "Value": "Yes",
      "ConcatenatedString": "apple,orange,pineapple"
    }
  ]
}

然后,您每key value对都进行遍历迭代,并过滤要映射的元素。