如何使用DataWeave在Mule 4中合并2个JSON负载

如何解决如何使用DataWeave在Mule 4中合并2个JSON负载

从两个不同的流中,我得到一个json输出有效负载,以及如何基于一个公共密钥将它们组合在一起。密钥是动态的,因此我想编写一个适用于任何密钥的通用数据编织。

输入1:

[
  {
    "CustomerID": "123","Name": "Maria","Phone": "030-0074321"
    
  },{
    "CustomerID": "56654","Name": "sdf","Phone": "030-6877452"
    
  }
]

输入2:

[
    {
      "OrderID": "10643","CustomerID": "123","Price": "200"
    },{
      "OrderID": "10692","Price": "566"
    },{
      "OrderID": "10702","CustomerID": "56654","Price": "546"
    }
  ]

预期输出:

[
   {
      "CustomerID":"123","Name":"Maria","Phone":"030-0074321","Details":[
         {
            "OrderID":"10643","Price":"200"
         },{
            "OrderID":"10692","Price":"566"
         }
      ]
   },{
      "CustomerID":"56654","Name":"sdf","Phone":"030-6877452","Details":[
         {
            "OrderID":"10702","Price":"546"
         }
      ]
   }
]

基于公共密钥(在此示例中为CustomerID),我想将两个输入组合在一起。 正如我提到的,所有键(CustomerID,Name,Phone,OrderID,Price)一直都不相同,它们是动态的。

有人可以帮我写一个动态的数据编织代码吗?

预先感谢

解决方法

这是我很快想到的:

%dw 2.0
output application/dw

var input1 = [
  {
    "CustomerID": "123","Name": "Maria","Phone": "030-0074321"
    
  },{
    "CustomerID": "56654","Name": "sdf","Phone": "030-6877452"
    
  }
]

var input2 = [
    {
      "OrderID": "10643","CustomerID": "123","Price": "200"
    },{
      "OrderID": "10692","Price": "566"
    },{
      "OrderID": "10702","CustomerID": "56654","Price": "546"
    }
  ]

fun combineByKey(in1,in2,k) = do {
    var groupedBy = in2 groupBy $[k]
    ---
    in1 map {
        ($),details: groupedBy[$[k]]
    }
}


---

combineByKey(input1,input2,"CustomerID")

//do {
//  var groupedBy = input2 groupBy $.CustomerID
//  ---
//  input1 map {
//      ($),//      details: groupedBy[$.CustomerID]
//  }
//}

从底部注释掉的表达式中可以看到,它并不长,所以我认为您不需要功能恕我直言。

从本质上讲,您只需要知道两个函数groupBymap,然后知道如何使用do {}创建闭包(也就是本地化的声明),最后知道如何动态访问字段。

我敢打赌,如果我花更多的时间,我应该能够提出更好的功能,但是现在就可以了:)

可能已经有一些内置函数可以执行此操作,但是我不知道。也许有人会指出。

,

此 dataweave 转换满足您提到的条件。

   

    %dw 2.0
    output application/json
    ---
    input1 map(value) -> using (id = value.CustomerID)
    {
       CustomerID: value.CustomerID,Name: value.Name,Phone:value.Phone,Details: (input2 filter ($.*'CustomerID' contains  id) map ($ mapObject (k,v) ->{
         (v):k
         } - "CustomerID"))
    }

,

也许您也可以使CommonKey成为动态的。我知道这可能是一个过大的杀伤力,但是我在这里就把它排除在外,以防它以任何可能的方式有所帮助。

DataGrid
,

您可以通过使用一些递归函数或仅通过获取键然后在 in1 in2 之间进行比较,然后进行重组以创建 { {1}} 。诀窍是创建一个 primaryKey ,它是所有commonKey的值。

尝试以下脚本。 in1 类似于主要参考,而 in2 是次要参考。要对其进行测试,请尝试在 in2 中添加 foreignKey 字段,并至少使用匹配值 Name Name 来自 CustomerID

in1
,

这是另一个公共密钥为动态的解决方案:

%dw 2.0
output application/json
import * from dw::core::Arrays
var inp1=[
  {
    "CustomerID": "123","Phone": "030-6877452"
    
  }
]
var inp2=[
    {
      "OrderID": "10643","Price": "546"
    }
  ]

//get all the keys from both the arrays
var inp1keys=((inp1 reduce(item,acc) -> item ++ acc) pluck $$) distinctBy $
var inp2keys=((inp2 reduce(item,acc) -> item ++ acc) pluck $$) distinctBy $
//get the matching key in the array
var matchingkey=((inp1keys  map (v0,k0) ->
{
    matched: if(inp2keys contains v0) v0 else null
}.matched) filter $ != null)[0]
---
/*
Steps for the script below:
1.Join both the array on the common key fetched dynamically above.
2.Remove the common key from the rigt part obtained after join.
3.After that merge the Details part for a given common key under a given common key id(achieved with the reduce)
*/
((join(inp1,inp2,(inp1) -> inp1."$(matchingkey)",(inp2) -> inp2."$(matchingkey)")) 
map (v0,k0) ->
{
    ((v0.l) ++ (Details:v0.r - matchingkey))
}) reduce (item,acc) ->  if( acc."$(matchingkey)" contains item."$(matchingkey)"[0])  
((acc - 'Details') ++ Details:[acc.Details,item.Details])
else [acc] + item

无论如何,从性能的角度来看,请谨慎使用此类脚本。 enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res