Rest Assured如何编写GPath表达式筛选my-type为SPECIAL的my-notes
GPath过滤表达式适配方案
问题说明
- 核心需求:编写带过滤逻辑的GPath表达式,从JSON响应中筛选
my-type字段值为SPECIAL的条目,提取对应条目下的my-notes内容 - 初始编写的错误表达式:
"data.my-node.nodes.findAll{it.'my-type'=='GENERAL'}.'my-nodes'"
- 故障表现:上述表达式无法从目标JSON结构中正确提取预期数据
待解析的目标JSON结构
{ "data": {"my-node": [ { "nodes": [ { "my-nodes": [{"my-note": "abcdefg"}], "my-type": "GENERAL" }], "my-instruction": null }, { "nodes": [ { "my-nodes": [{"my-note": "abcdefg"}], "my-type": "SPECIAL" }], "my-instruction": null }, { "nodes": [ { "my-nodes": [{"my-note": "oiugitoirtuhou"}], "my-type": "SPECIAL" }], "my-instruction": null }, { "nodes": [ { "my-nodes": [{"my-note": "ifuoirjhihj"}], "my-type": "SPECIAL" }], "my-instruction": null }, { "nodes": [ { "my-nodes": [{"my-note": "idfgdiufgdhsfuihdf"}], "my-type": "SPECIAL" }], "my-instruction": null }, { "nodes": [ { "my-nodes": [{"my-note": "iydfgsigdfgdgidsf"}], "my-type": "SPECIAL" }], "my-instruction": null } ]} }
错误原因
原表达式存在两处不符合JSON结构的问题:
- 路径层级错误:
data下的my-node是数组类型,无法直接访问数组的nodes属性,必须先遍历my-node数组的每个元素,才能读取元素内部的nodes字段 - 过滤条件不匹配:需求要求筛选
my-type值为SPECIAL的条目,原表达式写的是匹配GENERAL值
可用的正确GPath表达式
提取所有匹配条目的my-nodes字段
data.'my-node'*.nodes.flatten().findAll{it.'my-type' == 'SPECIAL'}.'my-nodes'
表达式各段逻辑说明:
data.'my-node':定位到data节点下的my-node数组*.nodes:使用展开运算符遍历my-node数组的每一项,取出每项中存储的nodes子数组flatten():将多层嵌套的数组合并为一维列表,简化后续过滤操作findAll{it.'my-type' == 'SPECIAL'}:筛选出列表中my-type字段值等于SPECIAL的所有条目'my-nodes':提取筛选后所有条目对应的my-nodes字段值
如需直接提取最内层的my-note文本内容
可使用扩展后的表达式,直接返回所有匹配的note文本列表:
data.'my-node'*.nodes.flatten().findAll{it.'my-type' == 'SPECIAL'}.'my-nodes'.flatten().'my-note'
该表达式执行后返回结果为:
["abcdefg", "oiugitoirtuhou", "ifuoirjhihj", "idfgdiufgdhsfuihdf", "iydfgsigdfgdgidsf"]
内容的提问来源于stack exchange,提问作者saba
相关产品推荐
相关产品推荐

