syed naveed
syed naveed

Reputation: 95

How to get value from Json using groovy script

Hi I am new to groovy and API Automation. I have the following Json and i want to add assertion to check cyclestartdate and cycleEnddate based on sequence number.

{
   "status" : "success",
   "locale" : "",
   "data" : {
      "periods" : [
         {
            "payCycleId" : "custompayperiod",
            "sequence" : 1,
            "cycleStartDate" : "2018-10-01",
            "cycleEndDate" : "2018-10-08"
         },
         {
            "payCycleId" : "custompayperiod",
            "sequence" : 2,
            "cycleStartDate" : "2018-10-09",
            "cycleEndDate" : "2018-10-16"
         }
      ]
   }
}

How do i check if sequence 1 cycleStartDate is 2018-10-01

Upvotes: 3

Views: 4345

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

Groovy provides JsonSlurper class that makes parsing JSON documents easier. Consider following example that reads JSON document as a String (it supports different initialization methods as well):

import groovy.json.JsonSlurper

def inputJson = '''{
   "status" : "success",
   "locale" : "",
   "data" : {
      "periods" : [
         {
            "payCycleId" : "custompayperiod",
            "sequence" : 1,
            "cycleStartDate" : "2018-10-01",
            "cycleEndDate" : "2018-10-08"
         },
         {
            "payCycleId" : "custompayperiod",
            "sequence" : 2,
            "cycleStartDate" : "2018-10-09",
            "cycleEndDate" : "2018-10-16"
         }
      ]
   }
}'''

def json = new JsonSlurper().parseText(inputJson)

assert json.data.periods.find { it.sequence == 1 }.cycleStartDate == '2018-10-01'

Having JSON document loaded you can extract data by accessing nested fields. For instance, json.data.periods gives you an access to the array stored in your JSON document. Then method find { it.sequence == 1 } returns a node from this array where sequence field is equal to 1. And lastly you can extract cycleStartDate and compare it with the expected date.

You can find more useful examples in Groovy's official documentation.

Upvotes: 3

Related Questions