【问题标题】:Mule DWL - Flatten json hierarchical elementsMule DWL - 展平 json 分层元素
【发布时间】:2020-06-11 22:33:26
【问题描述】:

我的 json 有效负载如下:

Attributes:{
    Contact:{
        Address:{
            PersonName:"John",
            Line1:"sdsds",
            Line2:"sdsdsd",
            SubAddress:{
                PersonName:"John",
                Line1:"ggghg",
                Line2:"xzxzxzx"
            }
        },
        Phone:{
            Home:"2323232323",
            Office:"4545454545"
        }
    },
    Id:"2343434",
    order:"3343434"
}

我想将层次结构展平到输出下方

Attributes:{
    Contact.Address.PersonName:"John",
    Contact.Address.Line1:"sdsds",
    Contact.Address.Line2:"sdsdsd",
    Contact.Address.SubAddress.PersonName:"John",
    Contact.Address.SubAddress.Line1:"ggghg",
    Contact.Address.SubAddress.Line2:"xzxzxzx",
    Contact.Phone.Home:"2323232323",
    Contact.Phone.Office:"4545454545",
    Id:"2343434",
    order:"3343434"
}

Attributes 元素可以包含任意数量的复杂元素,例如“Address”和“Contact”。在编码时,我们不会知道复杂元素的键值。 DWL 应该能够产生单级输出。想要在 Mule 3 中使用 dw1 进行这种扁平化的通用解决方案。请帮助。

【问题讨论】:

    标签: mule dataweave mule-component


    【解决方案1】:

    以下脚本递归地遍历有效负载并构造单个键值 配对对象

    %dw 1.0
    %output application/json
    %var payload = {"Attributes":{"Contact":{"Address":{"SubAddress":[{"PersonName1":"John","Line1":"ggghg","Line2":"xzxzxzx"},{"PersonName":"Jar","Line1":"ggghg","Line2":"xzxzxzx"}]},"Phone":{"Home":"2323232323","Office":"4545454545"}},"Id":"2343434","order":"3343434"}}
    %function constructKeys(oldKeys, newKey) oldKeys ++ '.' ++ newKey
    %function writeData(json ,output, keys)  json match {
                case is :null -> null,
                case is :array -> {(json map ((item, index) -> writeData(item, output, keys ++ index)))},
                case is :object -> {((json pluck $$) map writeData(json[$],output,constructKeys(keys,$)))},
                default -> output ++ {(keys[1 to -1]): json }
    }
    ---
    Attributes: writeData(payload.Attributes,{}, '')
    
    
    

    【讨论】:

    • 有没有办法捕获数组索引作为键的一部分:“Contact.Address.SubAddress.1.PersonName”:“John”,“Contact.Address.SubAddress.2.PersonName”: “约翰”,
    猜你喜欢
    • 2022-12-26
    • 2020-11-21
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 2018-10-01
    相关资源
    最近更新 更多