Karate框架筛选JSON响应字段返回空结果的问题求解
问题原因
- 用错了核心API:
karate.filter()仅适用于JSON数组的元素筛选,你当前操作的是单个JSON对象而非数组,自然返回空结果。 - 代码执行顺序错误:你在定义
result变量之前就调用print result.isbn,会直接触发变量未定义报错。 - 逻辑匹配错误:
filter的作用是保留符合判断条件的集合条目,你的需求是删除单个对象内的指定key,和筛选条目的逻辑完全不匹配。
正确实现方案
方案1:最简原生实现(推荐,无需自定义函数)
直接利用Karate对JSON的原生可变支持,判断isbn值匹配后删除对应key即可:
# 先将原始JSON赋值给result变量 * def result = { "isbn": "9781449325862", "title": "Git Pocket Guide", "subTitle": "A Working Introduction", "author": "Richard E. Silverman", "publish_date": "2020-06-04T08:48:39.000Z", "publisher": "O'Reilly Media", "pages": 234, "description": "This pocket guide is the perfect on-the-job companion to Git, the distributed version control system. It provides a compact, readable introduction to Git for new users, as well as a reference to common commands and procedures for those of you with Git exp", "website": "http://chimera.labs.oreilly.com/books/1230000000561/index.html" } # isbn值匹配时移除对应字段 * if (result.isbn == '9781449325862') delete result.isbn # 打印验证输出 * print result
执行后会直接返回移除了isbn字段的完整JSON对象,其余字段结构、值完全不变。
方案2:适配JSON数组批量处理场景
如果实际业务中返回的是书籍列表数组,需要批量把所有isbn为9781449325862的对象移除isbn字段,可以用karate.map()做遍历处理:
# 示例:result为书籍对象数组 * def result = [ {"isbn": "9781449325862", "title": "Git Pocket Guide", "author": "Richard E. Silverman"}, {"isbn": "9781449331818", "title": "Learning JavaScript Design Patterns", "author": "Addy Osmani"} ] * def processBook = function(book) { if (book.isbn == '9781449325862') delete book.isbn; return book } * def result = karate.map(result, processBook) * print result
提示:
karate.filter()仅用于集合元素筛选,不要用它做对象字段删除类操作。
内容的提问来源于stack exchange,提问作者malyalamvenu
相关产品推荐
相关产品推荐

