harshabongle
5 years agoOccasional Contributor
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
}
}
}
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 🙂