如何使用JSONPath 2.4获取符合条件的最后一个townhouse的features值?
获取目标features值的JSONPath 2.4表达式
原始JSON数据
{ "markets": { "US": { "homes": [ { "type": "house" }, { "type": "multifamily" }, { "type": "townhouse", "hoa": { "features": "dog park, covered parking" } }, { "type": "house" }, { "type": "multifamily" }, { "type": "townhouse", "hoa": { "features": "pool, snow removal" } } ] } } }
需求说明
需要编写JSONPath 2.4表达式,获取homes列表中**最后一个type为"townhouse"**的条目里的features字段值(该值为"pool, snow removal",且必然包含"pool")。
问题分析
你尝试过的以下表达式无法得到预期结果:
$.markets.US.homes[?(@.type == 'townhouse')][-1]$.markets.US.homes[?(@.type == 'townhouse')][-1:]$.markets.US.homes[?(@.type == 'townhouse')][@.length-1]$.markets.US.homes..hoa[?(@.features contains "pool")]
核心问题在于:[-1]、@.length-1并非JSONPath 2.4的标准语法,部分实现不支持;且部分表达式未精准定位到最后一个符合条件的条目并提取features字段。
正确表达式
表达式1(仅过滤type为townhouse,取最后一个的features)
$.markets.US.homes[?(@.type == 'townhouse')][last()].hoa.features
表达式2(同时过滤type和features包含pool的条件)
$.markets.US.homes[?(@.type == 'townhouse' && @.hoa.features contains 'pool')][last()].hoa.features
语法说明
[?(@.type == 'townhouse')]:过滤出所有type为townhouse的条目[last()]:JSONPath 2.4标准函数,用于获取数组的最后一个元素.hoa.features:精准定位到目标字段
内容的提问来源于stack exchange,提问作者Kinsey Bice
相关产品推荐
相关产品推荐

