[英]How to get an Array item using Script runner groovy script
我在 Jira 的腳本運行程序中使用 MSGraph API 和 groovy 腳本,以便通過他的 email 地址檢索 guets AD 用戶。
我用於執行此操作的代碼如下:
public String getGuestUserId(String AuthToken,String userEmail){
String _userId
def http = new HTTPBuilder(graph_base_user_url + "?")
http.request(GET) {
requestContentType = ContentType.JSON
//uri.query = [ $filter:"mail eq '$userEmail'"].toString()
uri.query=[$filter:"mail eq '$userEmail'"]
headers.'Authorization' = "Bearer " + AuthToken
response.success = { resp, json ->
_userId=json["value"]
}
// user ID not found : error 404
response.'404' = { resp ->
_userId = 'Not Found'
}
}
_userId
}
此調用的 output 如下:
[{businessPhones=[], displayName=user test, givenName=null, jobTitle=null,
mail=user1@gmail.com, mobilePhone=null, officeLocation=null, preferredLanguage=null,
surname=null, userPrincipalName=user1_gmail.com#EXT#@rlxcom.onmicrosoft.com, id=7982c558-
ba50-4380-9e94-114d8b340720}]
IT 代表陣列 object 的單個用戶 output。
僅檢索此返回數組的Id部分的方法是什么?
我已經嘗試使用以下方法直接從我的方法返回:
response.success = { resp, json ->
_userId=json["value"][0]["Id"]
但它不工作
==> 已更新
如果我只是使用以下代碼部分來查看解析 Json 是否正常,我會收到異常錯誤:
def json = new groovy.json.JsonSlurper().parseText ret
return json
groovy.json.JsonException: 期待 '}' 或 ',' 但得到的當前字符 'b' 的 int 值為 98
當前讀取的字符是 'b',int 值為 98,需要 '}' 或 '',但當前字符 'b' 的 int 值為 98 行號 1 索引號 2
==== 更新 2 ===
如果我將方法 json 響應更改為:
response.success = { resp, json ->
_userId=json["value"].toString()
}
返回值為 json:
String json=apiHelper.getGuestUserId(apiHelper.Token,email)
返回如下(注意沒有{})
[[businessPhones:[], displayName:serge cal test, givenName:null,
jobTitle:null, mail:calderara.serge@gmail.com, mobilePhone:null,
officeLocation:null, preferredLanguage:null, surname:null,
userPrincipalName:calderara.serge_gmail.com#EXT#@rlxcom.onmicrosoft.com,
id:7982c558-ba50-4380-9e94-114d8b340720]]
然后根據您的示例調用如下解析方法:
def retVal = new groovy.json.JsonSlurper().parseText (json)
return retVal.id.first()
然后它失敗了,與我最初的帖子相同,因為它不是 Json 格式的返回,而是一個數組項。
知道如何根據上面的返回字符串讓它工作嗎?
如果您需要獲取所有ID(通用解決方案):
String str = """{"value":[{"businessPhones":"[]", "displayName":"user test", "givenName":null, "jobTitle":null,
"mail":"user1@gmail.com", "mobilePhone":null, "officeLocation":null, "preferredLanguage":null, "surname":null,
"userPrincipalName":"user1_gmail.com#EXT#@rlxcom.onmicrosoft.com", "id":"7982c558-ba50-4380-9e94-114d8b340720"}]}"""
def json = new groovy.json.JsonSlurper().parseText str
def ids = json.value*.id
assert ['7982c558-ba50-4380-9e94-114d8b340720'] == ids
你的具體案例:
http.request(GET) {
//...
response.success = { resp, json ->
_userId = json.value[ 0 ].id
// or
_userId=json.value*.id.first()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.