如何在Groovy中从Jenkins HTTP响应获取JSON最后一个元素
Jenkins共享库函数获取JSON响应最后一项
原Groovy函数代码
/* 以下函数用于列出群组 */ def list_groups(server_url,each_group_name,authentication){ def groups_url = server_url + "/api/v1/groups" def response = httpRequest consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', customHeaders: [[maskValue: false, name: 'Authorization', value: authentication]], httpMode: 'GET', ignoreSslErrors: true, responseHandle: 'NONE', url: groups_url, validResponseCodes: '100:599' if(response.status == 404){ throw new Exception("服务器地址未找到!请提供正确的服务器URL。") } else{ if(response.status == 400 || response.status == 403){ throw new Exception("无效的访问令牌或访问令牌已过期!") } } def result = readJSON text: """${response.content}""" }
API响应内容
响应码:HTTP/1.1 200 OK
成功:状态码200在可接受范围100:599内
响应体:
[{"id":2,"name":"Default User"},{"id":3,"name":"fos"},{"id":4,"name": "kXR"},{"id":5,"name": "Sgh"},{"id":6,"name":"ksn"},{"id":7,"name":"ALb"}]
需求
需要从JSON响应体中获取最后一项({"id":7,"name":"ALb"}),通过Groovy将其打印并存入变量。
修改后的实现代码
/* 以下函数用于列出群组并获取最后一项 */ def list_groups(server_url, each_group_name, authentication){ def groups_url = server_url + "/api/v1/groups" def response = httpRequest consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', customHeaders: [[maskValue: false, name: 'Authorization', value: authentication]], httpMode: 'GET', ignoreSslErrors: true, responseHandle: 'NONE', url: groups_url, validResponseCodes: '100:599' if(response.status == 404){ throw new Exception("服务器地址未找到!请提供正确的服务器URL。") } else if(response.status == 400 || response.status == 403){ throw new Exception("无效的访问令牌或访问令牌已过期!") } // 解析JSON响应为Groovy列表 def result = readJSON text: response.content // 获取列表最后一项 def lastGroup = result.last() // 打印最后一项 println("获取到的最后一个群组:${lastGroup}") // 返回最后一项,供调用方使用 return lastGroup }
关键说明
- Groovy列表自带
last()方法,可直接获取列表的最后一个元素 lastGroup变量存储了目标数据,可在函数内部使用或返回给调用方- 通过
println直接打印该对象,控制台会输出格式化后的内容
内容的提问来源于stack exchange,提问作者Abilash
相关产品推荐
相关产品推荐

