Forum Discussion

trans-am's avatar
trans-am
Occasional Contributor
2 years ago
Solved

Getting elements from json list to varable

Let's say I have following json response list stored in "response" variable

 

import groovy.json.JsonSlurper
def response = context.expand( '${GetResponse#response}' ).toString() // get response data to string
log.info(response) // print the data list

{"list": [{"status": "ACTIVE", "Number": 123, "Version": "1.12"}]}

 Now I want to get e.g. status and put it to variable "currentStatus" and Number to "currentNumber". So how to do it?  I tried  few ways with JsonSlurper() but always getting "null" value

 

 

  • Thanks for confirming. It will be great help if you accept this as solution

4 Replies

  • ChrisAdams's avatar
    ChrisAdams
    Champion Level 3

    Hi,

     

    Here's some example Groovy script....

    import groovy.json.JsonSlurper;

    def slurper = new groovy.json.JsonSlurper();

    def result = slurper.parseText('{"list": [{"status": "ACTIVE", "Number": 123, "Version": "1.12"}]}');

    // Can we get the list?
    log.info(result.list);

    // Let's get the idividual values. Bear in mind, list is an array

    // this won't work as we're assuming list is an object, not an array....
    //log.info(request.list.status);

    // Access the list as an array. Note the props are case sensitive...
    log.info(result.list[0].status);
    log.info(result.list[0].Number);
    log.info(result.list[0].Version);

    // create a var....
    def status = result.list[0].status;

    return status;

     

  • try this

     

    def response = context.expand( '${GetResponse#response}' ).toString() 

     

    def parser = new JsonSlurper()
    def json = parser.parseText(response)

    def currentStatus = json.list[0].status
    def currentNumber = json.list[0].Number
    log.info currentStatus
    log.info currentNumber

    • trans-am's avatar
      trans-am
      Occasional Contributor

      Actually works. This line json.list[0].status helps. I am getting now values

  • Thanks for confirming. It will be great help if you accept this as solution