简体   繁体   中英

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.

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:

[{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.

What is the way to retrive only the Id part of this return Array?

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:

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

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

==== UPDATE 2 ===

IF I change my method json repsonse to be:

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

The return value is 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.

Any idea how to get it work based on return string above?

If you need to get all ids (general solution):

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()
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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