【问题标题】:Dataweave - Transform CSV structureDataweave - 转换 CSV 结构
【发布时间】:2021-12-23 04:11:18
【问题描述】:

我正在尝试使用 Dataweave 2.0 转换 .CSV 的结构

这是我的输入 csv 示例:

gaID,gender,age,city,state
GA1.3.332,male,20-30,,
GA1.3.1041d,female,30-40,Sao Paulo,Sao Paulo
GA1.3.1041d,,,Sao Paulo

我需要创建这个输出:

GA1.3.332^gender:male;age:20-30
GA1.3.1041d^gender:female;age:30-40;city:Sao Paulo;state:Sao Paulo
GA1.3.1041d^state:Sao Paulo

请注意,当输入属性为 null 时,它们不应出现在输出中,这就是我遇到的问题。

到目前为止,我有这段代码,但不完全符合我的需要,因为它编写了所有属性,即使是否为空。

%dw 2.0
output application/csv header=false, separator=';'
---
payload map {
 c1: $.gaID ++ "^" ++ "gender:" ++ $.gender,
 c2: "age:" ++ $.age,
 c3: "city:" ++ $.city,
 c4: "state:" ++ $.state,
 c5: "maritalStatus:" ++ $.martitalStatus,
 c6: "householdIncome:" ++ $.householdIncome,
 c7: "bradSegCustomer:" ++ $.bradSegCustomer,
 c8: "bradCustomer:" ++ $.bradCustomer,
 c9: "BankClientSegment:" ++ $.BankClientSegment,
 c10: "main_account:" ++ $.main_account,
 c11: "occupation:" ++ $.occupation,
 c12: "presenceofChildren:" ++ $.presenceofChildren,
}

我的代码输出:

GA1.3.332^gender:male;age:20-30;city:;state:
GA1.3.1041d^gender:female;age:30-40;city:Sao Paulo;state:Sao Paulo

【问题讨论】:

    标签: csv dataweave mulesoft


    【解决方案1】:

    我将它转换为动态的,除了 gaID 字段的特殊转换,然后添加条件以使用 filterObject() 过滤具有空值的元素。

    %dw 2.0
    output application/csv header=false, separator=';'
    ---
    payload map 
        ($ 
          filterObject ((value, key, index) -> !isEmpty(value))
          mapObject((value, key, index) -> 
            (key): if (key as String != "gaID") 
                        (key as String ++ ":" ++ value) 
                   else (value ++ "^") 
        )
    )
    

    输入:

    gaID,gender,age,city,state
    GA1.3.332,male,20-30,,
    GA1.3.1041d,female,30-40,Sao Paulo,Sao Paulo
    GA1.3.1041d,,,Sao Paulo
    

    输出:

    GA1.3.332^;gender:male;age:20-30
    GA1.3.1041d^;gender:female;age:30-40;city:Sao Paulo;state:Sao Paulo
    GA1.3.1041d^;city:Sao Paulo
    

    对于 CSV 格式,您无法删除字段之间的分隔符。如果第一个';'是一个问题,那么我们需要使用字符串输出并根据需要连接字段,尽管我们失去了 CSV 解决方案的一些简单性:

    %dw 2.0
    output application/java
    ---
    payload map 
        ($ 
            filterObject ((value, key, index) -> !isEmpty(value))
            mapObject((value, key, index) -> 
                (key): if (key as String != "gaID") 
                            (key as String ++ ":" ++ value) 
                    else (value ++ "^") 
            )
            pluck ($)
            reduce  ((item, acc="") -> acc ++ item ++";")
        ) reduce ($$ ++ "\n" ++ $)
    

    此脚本在每一行的末尾提供一个额外的;。如果这是一个问题,添加一个函数来删除它应该不难。

    【讨论】:

    • 感谢您的回复亚历克。我正在尝试了解如何更改您的代码以避免拥有 gaID^;在所有记录中
    • 我在测试中没有看到。您是否使用了与您的描述相同的输入?
    • 我在测试中添加了输入和输出,并稍微简化了脚本。
    • 从您的输出中,我怎样才能删除 ;在 ^ 之后
    • 我已经为后一种情况使用新脚本更新了我的答案。因为输出并不真正符合 CSV 格式,所以我开发了一个替代方案。
    猜你喜欢
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2017-12-23
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多