合并两个JSON文件,同时求和



我得到两个不同的文件,其中包含股票信息,我想将它们合并为一个文件,同时基于"pid"汇总数据。

payloadA

{
"order": [
{
"pid": "a",
"instock": "2"
},
{
"pid": "b",
"instock": "2"
},
{
"pid": "c",
"instock": "2"
}
]
}

payloadB

{
"order": [
{
"pid": "c",
"instock": "2"
},
{
"pid": "d",
"instock": "2"
}
]
}

结果payloadA

{
"order": [
{
"pid": "a",
"instock": "2"
},
{
"pid": "b",
"instock": "2"
},
{
"pid": "c",
"instock": "4"
},
{
"pid": "c",
"instock": "2"
}
]
}

但是我正在挣扎的是边缘情况:

  • pid可能同时存在于两个数据集中,也可能只存在于其中一个数据集中
  • payloadB可能为空
{
"order": []
}

您可以尝试以下DataWeave表达式:

%dw 2.0
output application/json
import * from dw::core::Arrays
var payloadA = {
"order": [
{
"pid": "a",
"instock": "2"
},
{
"pid": "b",
"instock": "2"
},
{
"pid": "c",
"instock": "2"
}
]
}
var payloadB = {
"order": [
{
"pid": "c",
"instock": "2"
},
{
"pid": "d",
"instock": "2"
}
]
}
---
"order": outerJoin(payloadA.order, payloadB.order, (itemA) -> itemA.pid, (itemB) -> itemB.pid) map (item, index) -> {
"pid": item.l.pid default item.r.pid,
"instock": (item.l.instock default 0) + (item.r.instock default 0)
}

输出:

{
"order": [
{
"pid": "a",
"instock": 2
},
{
"pid": "b",
"instock": 2
},
{
"pid": "c",
"instock": 4
},
{
"pid": "d",
"instock": 2
}
]
}

相关内容

  • 没有找到相关文章

最新更新