DataWeave中[?($.Role=='Account')]表达式的含义解析
DataWeave中
[?($.Role=='Account')]的含义解析 背景信息
输入JSON载荷
{ "relatedParty": [ { "id": "001", "Role": "Account" }, { "id": "006", "Role": "OpportunityId" } ] }
用于提取值的DataWeave表达式
payload..relatedParty[0][?($.Role=='Account')].id[0]
核心解析
[?($.Role=='Account')]是DataWeave的数组过滤表达式,作用是从目标数组中筛选出符合指定条件的元素,对应你熟悉的C#/.NET中的LINQ Where()方法,具体拆解如下:
[?()]:是DataWeave中数组过滤的语法标识,只要看到这个结构,就代表要对前面的数组进行条件筛选$:代表遍历数组时的当前元素,等同于C# LINQ里collection.Where(x => ...)中的x$.Role=='Account':具体的过滤条件,检查当前元素的Role属性值是否严格等于字符串"Account"
在你的示例中,这个过滤表达式会从relatedParty数组中选中Role为Account的对象(即{"id": "001", "Role": "Account"}),后续的.id[0]则会提取该对象的id值。
C#/.NET类比写法
如果用C#实现相同的筛选逻辑,代码大致如下:
public class RelatedParty { public string Id { get; set; } public string Role { get; set; } } // 模拟输入数据 var relatedParties = new List<RelatedParty> { new RelatedParty { Id = "001", Role = "Account" }, new RelatedParty { Id = "006", Role = "OpportunityId" } }; // 筛选Role为Account的元素并提取Id var accountId = relatedParties.Where(x => x.Role == "Account").FirstOrDefault()?.Id;
这里的Where(x => x.Role == "Account")就和DataWeave中的[?($.Role=='Account')]功能完全一致。
内容的提问来源于stack exchange,提问作者user2260040
相关产品推荐
相关产品推荐

