我有一个基于 Mulesoft 示例的 Dataweave 脚本https://docs.mulesoft.com/dataweave/latest/dataweave-cookbook-map-based-on-an-external-definition
我正在尝试使用外部字段映射将 CSV 文件的内容映射到 Apex 对象。但为了使用 DataWeave 交互式学习网页,我现在只是尝试将其转换为 JSON。
这是我的脚本,我终于开始工作了(某种程度上)
%dw 2.0
input csvData application/csv
input fieldMappings application/json
input objectProperties application/json
var apexClass = objectProperties.ObjectName
output application/json
---
csvData map ((row) -> (
fieldMappings map (fieldMapping) ->
(fieldMapping.target) : if(row[fieldMapping.source] != "") row[fieldMapping.source] else fieldMapping."defaultValue")
)
csv数据很简单:
First Name,Last Name,Title,Height,Color
Jane, Austin, CEO,7,blue
Bob, Smith, COO, 6,red
我的 fieldMappings 同样简单:
[
{
"source": "First Name",
"target": "FirstName"
},
{
"source": "Last Name",
"target": "LastName"
},
{
"source": "Title",
"target": "Title"
},
{
"source": "Height",
"target": "Height__c"
},
{
"source": "Importance",
"target": "Priority__c"
},
{
"source": "Interests",
"target": "Hobbies__c"
}
]
注意:我尝试过如下格式,但最终放弃了,因为我无法弄清楚如何迭代每个属性
{
"First Name" : "FirstName",
"Last Name" : "LastName"
}
无论如何,使用源/目标概念,我能够得到这样的输出:
[
[
{
"FirstName": "Jane"
},
{
"LastName": " Austin"
},
{
"Title": " CEO"
},
{
"Height__c": "7"
},
{
"Priority__c": null
},
{
"Hobbies__c": null
}
],
[
{
"FirstName": "Bob"
},
{
"LastName": " Smith"
},
{
"Title": " COO"
},
{
"Height__c": " 6"
},
{
"Priority__c": null
},
{
"Hobbies__c": null
}
]
]
但我想要的是
[
{
"FirstName": "Jane",
"LastName": " Austin",
"Title": " CEO",
"Height__c": "7",
"Priority__c": null,
"Hobbies__c": null
},
{
"FirstName": "Bob",
"LastName": " Smith",
"Title": " COO",
"Height__c": " 6",
"Priority__c": null,
"Hobbies__c": null
}
]
我尝试过 flatten(),我尝试过在各个级别上用作对象......不行。
我最近取得了一些成功
csvData map ((row) ->
fieldMappings map (fieldMapping) ->
(fieldMapping.target) : if(row[fieldMapping.source] != "") row[fieldMapping.source] else fieldMapping."defaultValue")
reduce ($$ ++ $)
)
但是我添加的那一刻
作为对象到最后我得到一个错误
无法将函数 ((row:Any) -> ???) 强制转换为对象
大家有什么想法吗?
好吧,所以我想发布问题就足以找到答案。答案是
的组合减少($$ ++ $)
这有助于将键/值对数组减少为单个 JSON 对象
并在函数周围放置适当的 parens() 以包含 fieldMappings 和 reduce
然后能够将 as 对象放在reduce之后,但在吐出对象数组的函数结束之前
当我认真思考时,这是有道理的,但我是 DataWeave 脚本的新手,因此嵌套函数的概念不是我熟悉的东西。
无论如何,对于那些对此感兴趣的人来说,这是有效的:
%dw 2.0
input csvData application/csv
input fieldMappings application/json
input objectProperties application/json
var apexClass = objectProperties.ObjectName
output application/apex
---
csvData map ((row) ->
(
(
fieldMappings map (fieldMapping) ->
(fieldMapping.target) : if(row[fieldMapping.source] != "") row[fieldMapping.source] else fieldMapping."defaultValue"
)
reduce ($$ ++ $)
) as Object
)