简体   繁体   English

如何使用脚本运行程序 groovy 脚本获取数组项

[英]How to get an Array item using Script runner groovy script

I am using MSGraph API and groovy scrip in script runner for Jira in order to retrieve a guets AD user by his email adress.我在 Jira 的脚本运行程序中使用 MSGraph API 和 groovy 脚本,以便通过他的 email 地址检索 guets AD 用户。

The code I am using for doing this is as below:我用于执行此操作的代码如下:

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
    } 

The output of this call is as below:此调用的 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 represent a single user output of an Array object. IT 代表阵列 object 的单个用户 output。

What is the way to retrive only the Id part of this return Array?仅检索此返回数组的Id部分的方法是什么?

I have already try to return from my method directly using:我已经尝试使用以下方法直接从我的方法返回:

response.success = { resp, json ->
_userId=json["value"][0]["Id"]

But it is not working但它不工作

==> Upated ==> 已更新

If I am just using the following code part to see if the parsing Json is ok I get an exception error:如果我只是使用以下代码部分来查看解析 Json 是否正常,我会收到异常错误:

def json = new groovy.json.JsonSlurper().parseText ret
return json

groovy.json.JsonException: expecting '}' or ',' but got current char 'b' with an int value of 98 groovy.json.JsonException: 期待 '}' 或 ',' 但得到的当前字符 'b' 的 int 值为 98

The current character read is 'b' with an int value of 98 expecting '}' or ',' but got current char 'b' with an int value of 98 line number 1 index number 2当前读取的字符是 'b',int 值为 98,需要 '}' 或 '',但当前字符 'b' 的 int 值为 98 行号 1 索引号 2

==== UPDATE 2 === ==== 更新 2 ===

IF I change my method json repsonse to be:如果我将方法 json 响应更改为:

response.success = { resp, json ->
            _userId=json["value"].toString()
        }

The return value is json:返回值为 json:

String json=apiHelper.getGuestUserId(apiHelper.Token,email)

is return as as below (notice that there are no {})返回如下(注意没有{})

[[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]]

Calling then you parse method as below as per your sample:然后根据您的示例调用如下解析方法:

def retVal = new groovy.json.JsonSlurper().parseText (json) 
return retVal.id.first()

Then it fails with same exception of my initial post because it is not a Json format return but an array item already.然后它失败了,与我最初的帖子相同,因为它不是 Json 格式的返回,而是一个数组项。

Any idea how to get it work based on return string above?知道如何根据上面的返回字符串让它工作吗?

If you need to get all ids (general solution):如果您需要获取所有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

Your concrete case:你的具体案例:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM