JSON含连字符键时Karate中出现PolyglotException问题求助
Karate中访问含连字符的JSON键的解决方法
当JSON键包含连字符(如示例中的get-book-by-id),直接使用点语法(response.attribute.links.get-book-by-id)会触发ReferenceError: 'book' is not defined错误——原因是Karate的JS引擎会将连字符解析成减号,把get-book-by-id误识别为算术表达式。
解决方法:
- 使用括号+单/双引号包裹带连字符的键,示例:
// 访问href属性 response.attribute.links['get-book-by-id'].href // 或者双引号写法 response.attribute.links["get-book-by-id"].title - 在Karate断言中应用该语法,完整示例:
Given url '/v1/books/1234' When method get Then status 200 And match response.attribute.links['get-book-by-id'].href == '/v1/books/1234' And match response.attribute.links["get-book-by-id"].title == 'get-book-by-id' - 也可以用
$表达式结合双引号包裹键:Then match $response.attribute.links."get-book-by-id".href == '/v1/books/1234'
内容的提问来源于stack exchange,提问作者u238825
相关产品推荐
相关产品推荐

