如何用JMESPath按group_name匹配返回groups和group_elements?
解决方案
你的问题核心是对象类型的数据不能直接用数组过滤符[?]——groups和group_elements都是键值对对象,而非数组,必须先把对象转换为数组才能进行过滤,最后再组合需要的结果。
最终JMESPath表达式
[0].changed_resource_value | { groups: groups.*[?group_name == 'contact_information_address'], group_elements: group_elements.*[?group_name == 'contact_information_address'] }
表达式拆解
[0].changed_resource_value:直接定位到原数组第一个元素里的changed_resource_value对象,简化后续表达式。groups.*:将groups对象的所有值转为数组,这样才能使用[?]过滤条件。[?group_name == 'contact_information_address']:在转换后的数组中,筛选出group_name精确匹配目标值的条目。{groups:..., group_elements:...}:构造新对象,把过滤后的groups和group_elements结果分别存入对应键中。
执行结果
应用该表达式后,会得到如下符合需求的结果:
{ "groups": [ { "group_name": "contact_information_address", "group_path": "group_elements.contact_information_address" } ], "group_elements": [ { "new_value": "some city", "old_value": "", "group_name": "contact_information_address", "group_path": "group_elements.contact_information_address", "element_name": "city" } ] }
你之前的表达式失败原因
[*].changed_resource_value.group_elements[?group_name == 'contact_information_address']:group_elements是对象而非数组,[?]无法直接作用于对象,因此返回空结果。[*].changed_resource_value.group_elements.*[?group_name == 'contact_information_address']:.*确实把对象转成了数组,但这条表达式只处理了group_elements,没包含groups的内容,你看到的false大概率是工具的显示问题,实际它能返回符合条件的group_elements条目。
内容的提问来源于stack exchange,提问作者Asdfg
相关产品推荐
相关产品推荐

