user4287996
user4287996

Reputation: 3

Parsing JSON response using Groovy and filtering for an element based on character count & another condition

I'm new to Groovy but using it to extract responses from JSON response stored in a file.

Below is a snippet of the JSON:

"attachments": [
        {
            "type": "AttachmentText",
            "text": "Line 1"
        },
        {
            "type": "AttachmentText",
            "text": "This is a different text and can be anything but always > 8 characters"
        }
    ],

I'm trying to get the text based on the condition that the text in the first case is always < 8 characters whereas the text in the second case is always >8 characters - there is no other way to distinguish the attachment elements otherwise. However my code only gives me 1 of the responses.

{
    def jsonSlurper = new JsonSlurper()
    def object = jsonSlurper.parseText(jsontocsv.toString())

    def array1 =  object.attachments

    if(array1 != null && !array1.isEmpty())
    {
        for(def i =0; i<object.attachments.size();i++)
        {
             if(object.attachments[i].type=="AttachmentText" && object.attachments[i].text.length()>8) {

                varaiable1 = RString.of(object.attachments[i].text.toString())
             }
             else{
                 variable2 = RString.of("Nothing here")
             }
         }
    }
    else {
        variable3 = RString.of("No attachments")
    }
}

I'm expecting that my variable1 will show response This is a different text and can be anything but always > 8 characters but I keep getting Nothing here instead.

Any idea how to fix this?

Upvotes: 0

Views: 999

Answers (1)

billjamesdev
billjamesdev

Reputation: 14640

Maybe something like this?

    def methodReturningLongText()
    {
        def jsonSlurper = new JsonSlurper()
        def object = jsonSlurper.parseText(jsontocsv.toString())
        def variable1 = RString.of("No attachments")
        def array1 =  object.attachments

        if(array1)
        {
            variable1 = RString.of("Nothing here")
            for(def i =0; i<array1.size();i++)
            {
                 if(object.attachments[i].type=="AttachmentText" && object.attachments[i].text.length()>8) {

                    variable1 = RString.of(object.attachments[i].text.toString());
                    break;
                 }
             }
        }
        return variable1
    }

Notes:

  1. defined method signature
  2. defined result variable1 with default
  3. used groovy-truthiness test in if (array1)
  4. used same result variable1 in all statements computing return value
  5. added break statement, so looping will stop after long value is found
  6. use of default values and pre-setting the "Nothing here" removes the need for else blocks.

Upvotes: 1

Related Questions