如何用 payload2 的相应值重新排列 payload1

How to re-arrange the payload1 with the corresponding values of payload2

我是 Mule 的新手并且遇到了一个场景。

Payload1 是从 csv 文件中获取的,payload2 是传入的 payload; Payload2 可能有多个对象。输出字段需要根据 payload1(即 csv 格式)和 payload2 的相应值进行排列。比较需要全部小写。

payload1 = "Name,Roll Number,Standard,Name of School,Address,Marks in Maths"   //this is an input from a csv file

//below is the input from different payload which is in camelcase.
payload2 = [
  {
    "address": "Street 123",
    "standard": "IV",
    "marksInMaths": "90",
    "rollNumber": "5",
    "name": "XYZ",
    "nameofSchool": "Best School"
}]

所需输出:

[{
   "Name" : "XYZ",
   "Roll Number": "5",
   "Standard" : "IV",
   "Name of School": "Best School", 
   "Address": "Street 123",
   "Marks in Maths": "90"
}]

我怎样才能做到这一点?

除了映射之外,您还需要注意阅读 CSV 的方式。如果您不禁用 CSV reader 中的 headers(读取操作上的 mime-type 属性),有效负载将为空 collection(因为您有一个 collection 共 object 没有 object,只有字段名称作为元数据)。另一种选择是将 CSV 读取为 plain/text,然后使用 splitBy 函数获取名称数组。

%dw 2.0
output application/json

// Be aware that I disable the headers to get them as values. If not it is not possible with CSV. Another way is to read it as text and then use splitBy
var payload1 = read("Name,Roll Number,Standard,Name of School,Address,Marks in Maths", "application/csv", {header: false})

var payload2 = [
  {
    "address": "Street 123",
    "standard": "IV",
    "marksInMaths": "90",
    "rollNumber": "5",
    "name": "XYZ",
    "nameofSchool": "Best School"
}]

// remove spaces and apply lowercase
fun normalize(value:String) = lower(dw::core::Strings::remove(value," "))
fun normalize(value:Object) = 
    value mapObject ((value, key, index) -> {(normalize(key)): value})


var namesMap = payload1[0] mapObject (value, key, index) -> 
    (normalize(value)): value
---

payload2 map ((item, index) -> 
    do {
        var normalizedItem = normalize(item)
        ---
        // iterate the namesMap to get the right order
        namesMap mapObject ((value, key, index) -> 
            // get the key from the namesMap and look the value in the payload2's item
            (value): normalizedItem[key]
        )
    }

神奇的是在映射之前创建了 namesMap,这样就很容易创建映射了。

编辑:原来的代码是错误的。它只匹配单个字符串键。