Dataweave 多级动态选择器
Dataweave multilevel dynamic selector
作为请求的一部分,我收到了带有一组字段的映射,如下所示:
{
"mapping": {
"targetField1": "a.b.sourceField1",
"targetField2": "a.c.sourceField2"
}
}
然后,我调用一个响应如下的服务:
{
"a": {
"b": {
"sourceField1": "sourceValue1"
},
"c": {
"sourceField2": "sourceValue2"
}
}
}
最后,我需要使用请求中的映射来动态映射响应,以生成如下内容:
{
"targetField1": "sourceValue1",
"targetField2": "sourceValue2"
}
当映射都在同一级别时,这很容易,因为它只使用 ["sourceField1"]
选择器,但我正在努力让多级别工作(类似于 "a.b.sourceField1"
)。支持数组,比如 "a.x[2].sourceFieldX"
我想这是另一个故事...
这会做你想做的并支持数组。
%dw 2.0
output application/json
fun getField(payload: Any, field: String) = do {
var path = field splitBy '.' reduce((pathPart, path=[]) ->
if (pathPart contains '[') do {
var pieces = pathPart splitBy '['
---
pieces reduce((piece,subPath=path) ->
if (piece contains ']') subPath << (piece replace ']' with '') as Number
else subPath << piece
)
}
else path << pathPart
)
---
getField(payload, path)
}
fun getField(payload: Any, field: Array) =
if (sizeOf(field) == 1) payload[field[0]]
else getField(payload[field[0]], field[1 to -1])
var inData = {
"a" : {
"b" : {
"sourceField1": [{ "value": "sourceValue11" }]
},
"c" : {
"sourceField2": "sourceValue2"
}
}
}
var mappingData = {
"mapping": {
"targetField1": "a.b.sourceField1[0].value",
"targetField2": "a.c.sourceField2"
}
}
---
mappingData.mapping mapObject (($$): getField(inData, $))
输出:
{
"targetField1": "sourceValue11",
"targetField2": "sourceValue2"
}
作为请求的一部分,我收到了带有一组字段的映射,如下所示:
{
"mapping": {
"targetField1": "a.b.sourceField1",
"targetField2": "a.c.sourceField2"
}
}
然后,我调用一个响应如下的服务:
{
"a": {
"b": {
"sourceField1": "sourceValue1"
},
"c": {
"sourceField2": "sourceValue2"
}
}
}
最后,我需要使用请求中的映射来动态映射响应,以生成如下内容:
{
"targetField1": "sourceValue1",
"targetField2": "sourceValue2"
}
当映射都在同一级别时,这很容易,因为它只使用 ["sourceField1"]
选择器,但我正在努力让多级别工作(类似于 "a.b.sourceField1"
)。支持数组,比如 "a.x[2].sourceFieldX"
我想这是另一个故事...
这会做你想做的并支持数组。
%dw 2.0
output application/json
fun getField(payload: Any, field: String) = do {
var path = field splitBy '.' reduce((pathPart, path=[]) ->
if (pathPart contains '[') do {
var pieces = pathPart splitBy '['
---
pieces reduce((piece,subPath=path) ->
if (piece contains ']') subPath << (piece replace ']' with '') as Number
else subPath << piece
)
}
else path << pathPart
)
---
getField(payload, path)
}
fun getField(payload: Any, field: Array) =
if (sizeOf(field) == 1) payload[field[0]]
else getField(payload[field[0]], field[1 to -1])
var inData = {
"a" : {
"b" : {
"sourceField1": [{ "value": "sourceValue11" }]
},
"c" : {
"sourceField2": "sourceValue2"
}
}
}
var mappingData = {
"mapping": {
"targetField1": "a.b.sourceField1[0].value",
"targetField2": "a.c.sourceField2"
}
}
---
mappingData.mapping mapObject (($$): getField(inData, $))
输出:
{
"targetField1": "sourceValue11",
"targetField2": "sourceValue2"
}