Forum Discussion

krogold's avatar
krogold
Regular Contributor
3 years ago
Solved

groovy - list parsing fails if it contains one element

Hello,

I often use jsonslurper to parse lists returned by test steps, but I have a case where it fails.

I have a testStep that is a call to an API, it returns a list of elements such as ["fim:device:LIGHT:1810","fim:device:LIGHT:1810", etc.]

In the next step I want to parse this list, so I use a jSonSlurper to convert it into an array doing

def light_list = context.expand( '${get all light devices#testResponse#$[\'result\']}' )
log.info light_list // ["fim:device:LIGHT:1810","fim:device:LIGHT:1811"]
log.info light_list.getClass() //=> string
def jsonSlurper = new groovy.json.JsonSlurper()
light_array = jsonSlurper.parseText(light_list)
light_array.each{
log.info it // => lists my two items
}

However I encounter a failure if that list contains only one element !

in that case

log.info light_list // [fim:device:LIGHT:1810]

which leads to a failure when I try to parse it with the jSonSlurper ...

the response from the previous step is a String, in both cases,

How can I ensure that the 'format' does not change ?

 

 

 

9 Replies

  • nmrao's avatar
    nmrao
    Champion Level 3

    The response does not seem to be a valid json or json array. Isn't it?

    ["fim:device:LIGHT:1810","fim:device:LIGHT:1810", etc.]

     

    • krogold's avatar
      krogold
      Regular Contributor

      it's just for the example, you can see it better in the code example

      • nmrao's avatar
        nmrao
        Champion Level 3
        Are you referring to
        ["fim:device:LIGHT:1810","fim:device:LIGHT:1811"] => this is not json or json array.
        Can you please provide the sample response ?