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

Karate.get()方法针对不存在的JSONPath无法返回指定默认值问题

Karate.get() JSONPath 默认值不生效的异常问题

问题描述

Karate官方文档说明,karate.get() 方法在变量或JSONPath不存在时会返回null,且可通过第二个参数指定默认值覆盖。但实际测试发现:

  • 针对不存在的变量,方法能正常返回指定默认值;
  • 针对不存在的JSONPath,返回#notpresent,无法被第二个参数覆盖。

测试用例

测试用JSON文档

{
"store": {
    "book": [
        {
            "category": "reference",
            "author": "Nigel Rees",
            "title": "Sayings of the Century",
            "price": 8.95
        },
        {
            "category": "fiction",
            "author": "Evelyn Waugh",
            "title": "Sword of Honour",
            "price": 12.99
        },
        {
            "category": "fiction",
            "author": "Herman Melville",
            "title": "Moby Dick",
            "isbn": "0-553-21311-3",
            "price": 8.99
        },
        {
            "category": "fiction",
            "author": "J. R. R. Tolkien",
            "title": "The Lord of the Rings",
            "isbn": "0-395-19395-8",
            "price": 22.99
        }
    ],
    "bicycle": {
        "color": "red",
        "price": 19.95
    }
},
"expensive": 10
}

测试代码及结果

// 变量测试正常
* def df = 12
* def v741 = karate.get("df", "100")
* print "v741", v741 // 输出=12,因变量'df'存在
* v741 = karate.get("df1", "100")
* print "v741", v741 // 输出=100,因变量'df1'不存在

// JSONPath测试异常
* def v74 = karate.get("$jsonObject.store.book[1].author1", 100)
* print "v74", v74 // 输出=#notpresent

后续确认的其他异常场景

已确认这是Karate的Bug,还存在以下不符合文档描述的情况:

  • print karate.get("jsonObject.store.book[*].author", 100):应返回作者数组,但实际返回100
  • print karate.get("$jsonObject.store.book[*].author", 100):返回正确的作者数组

根据文档,当JSONPath无结果时应返回指定默认值,但上述实际表现与文档不符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 21:36:16