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

csv to json conversion where some tags may not come in random

我有一个如下所示的 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)

提前致谢,

阿诺普

这是我的答案。

%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。这个returns

{
  "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 对并过滤你想要映射的元素。