如何用JsonPath按数组值过滤提取指定字段?
按locationCode过滤提取locationLegalName的JsonPath表达式
针对特定编码的提取示例
提取
locationCode为CC024对应的locationLegalName:$..locations[?(@.locationCode == 'CC024')].locationLegalName执行结果:
["Hotel Punta Cana"]提取
locationCode为CC021对应的locationLegalName:$..locations[?(@.locationCode == 'CC021')].locationLegalName执行结果:
["Restaurant Punta Cana"]
表达式解析
$..locations:递归遍历整个JSON结构,定位所有locations数组,无需关心其所在层级[?(@.locationCode == 'XXX')]:过滤数组元素,仅保留locationCode等于目标值的项,@指代当前遍历的数组元素.locationLegalName:从过滤后的元素中提取指定字段
优化:直接返回单个字符串(部分实现支持)
如果你的JsonPath工具支持索引取值,可以直接获取第一个匹配结果的字符串形式:
$..locations[?(@.locationCode == 'CC024')].locationLegalName[0]
执行结果:"Hotel Punta Cana"
注意:不同JsonPath实现(如Jayway、jsonpath-plus)可能存在语法细节差异,上述表达式为通用标准写法,适配多数主流工具。
内容的提问来源于stack exchange,提问作者Umer Shahid
相关产品推荐
相关产品推荐

