0

我有一个 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)

提前致谢,

阿努普

4

1 回答 1

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"
    }
  ]
}

然后你用 pluck 对每一key value对进行迭代并过滤你想要映射的元素。

于 2019-05-21T11:43:45.757 回答