Forum Discussion

harshabongle's avatar
harshabongle
Occasional Contributor
5 years ago

How to extract and build an array of unique values of a field from an array?

I want to extract a set of unique proceduresId values from the response i.e. [211, 324, 167]

Sample response:

{
"result" : {
"propertiesOPC" : [
{
"phasePropertyId" : 3890,
"proceduresId" : 211
},
{
"phasePropertyId" : 3890,
"proceduresId" : 211
},
{
"phasePropertyId" : 3890,
"proceduresId" : 324
},
{
"phasePropertyId" : 3890,
"proceduresId" : 167
},
{
"phasePropertyId" : 3890,
"proceduresId" : 167
}

}

}

  • harshabongle :

     

    You can use below code to extract only unique elements:

    import groovy.json.JsonSlurper
    def jsonSlurper = new JsonSlurper().parseText(res)
    def arrSize = jsonSlurper.result.propertiesOPC.size()
    HashSet<Integer> uniqueID_set = new HashSet<Integer>();
    for(int i = 0 ; i < arrSize ; i++){
    	log.info jsonSlurper.result.propertiesOPC[i].proceduresId
    	uniqueID_set.add(jsonSlurper.result.propertiesOPC[i].proceduresId)
    }
    log.info uniqueID_set

     

    Hope this will help you in resolving your issue 🙂

  • harshabongle :

     

    You can use below code to extract only unique elements:

    import groovy.json.JsonSlurper
    def jsonSlurper = new JsonSlurper().parseText(res)
    def arrSize = jsonSlurper.result.propertiesOPC.size()
    HashSet<Integer> uniqueID_set = new HashSet<Integer>();
    for(int i = 0 ; i < arrSize ; i++){
    	log.info jsonSlurper.result.propertiesOPC[i].proceduresId
    	uniqueID_set.add(jsonSlurper.result.propertiesOPC[i].proceduresId)
    }
    log.info uniqueID_set

     

    Hope this will help you in resolving your issue 🙂

    • sonya_m's avatar
      sonya_m
      SmartBear Alumni (Retired)

      Awesome! Thank you for helping, Himanshu!

       

      harshabongle was this the solution you were looking for?