You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何让JsonPath查询返回单个字符串而非数组结果

JsonPath获取单个字符串值而非数组的解决方法

我使用JsonPath查找单个值,但返回结果为数组,需要获取字符串类型的结果。

我的JSON数据如下:

{
    "id": 111,
    "name": "abc",
    "collectorDescription": "abc xyz",
    "customProperties": [
        {
            "name": "this.id",
            "value": "49271"
        },
        {
            "name": "this.Interval",
            "value": "30"
        },
        {
            "name": "this.categories",
            "value": ""
        }
    ],
    "upTimeInSeconds": 0,
    "deletedTimeInMs": 0
}

我原本用来获取"this.id"对应value的JsonPath表达式为:

$.customProperties[?(@.name == 'this.id')].value

该表达式返回的结果是数组:

[
  "49271"
]

但我期望得到字符串类型的结果:

"49271"

我尝试了以下几种表达式组合,但均未成功:

$.customProperties[:1][?(@.name == 'this.id')].value
$.customProperties[0][?(@.name == 'this.id')].value
$.customProperties[?(@.name == 'this.id')].value[0] ... etc

正确解决方式

根据你使用的JsonPath实现不同,可采用以下两种有效写法:

  1. 路径末尾直接索引(主流实现支持)
    直接在过滤后的value数组后添加[0],指定取第一个元素:

    $.customProperties[?(@.name == 'this.id')].value[0]
    

    如果你的实现不支持这种链式索引,可改用括号包裹过滤路径再取索引:

    $($.customProperties[?(@.name == 'this.id')].value)[0]
    
  2. 针对Jayway JsonPath库的写法
    若使用Jayway JsonPath,除了上述写法外,还可以通过调用时指定返回类型来直接获取字符串:

    String targetValue = JsonPath.read(jsonContent, "$.customProperties[?(@.name == 'this.id')].value", String.class);
    

为什么之前的尝试失败

  • $.customProperties[:1][?(@.name == 'this.id')].value:部分JsonPath实现不支持先切片再过滤的顺序,导致无法正确匹配
  • $.customProperties[0][?(@.name == 'this.id')].value:[0]已取出单个对象,再用[?()]过滤单个对象是无效语法,因此返回空或错误结果

内容的提问来源于stack exchange,提问作者user5489618

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 11:47:14