avidCoder
avidCoder

Reputation: 490

How to get the particular array node from JSON and print one by one using groovy?

I have the following JSON format :-

{
"id": "102",
"brand": "Disha",
"book": [{
    "slr": "EFTR",
    "description": "Grammer",
    "data": "TYR",
    "rate": true,
    "numberOfPages": 345,
    "maxAllowed": "12",
    "currentPage": 345
    },
    {
    "slr": "EFRE",
    "description": "English",
    "data": "TYR",
    "rate": true,
    "numberOfPages": 345,
    "maxAllowed": "12",
    "currentPage": 345
    },
    {
    "slr": "BGTR",
    "description": "French",
    "data": "TYR",
    "rate": true,
    "numberOfPages": 345,
    "maxAllowed": "12",
    "currentPage": 345
    }]
}

I want to write the groovy code to get the book array and print it one by one and before that I need to count the array node for book also.

I have tried below code:-

def response = context.expand( '${book#Response}' );
def slurper = new JsonSlurper();
String inputJSON = slurper.parseText(response)
def strFinalValueToRead = "\$." + "book[0]"
def strActualValue = parse(inputJSON).read(strFinalValueToRead).toString()

log.info strActualValue

I am getting error as

com.jayway.jsonpath.InvalidJsonException: net.minidev.json.parser.ParseException: Unexpected End Of File.

Any help would be appreciated.

Upvotes: 3

Views: 2088

Answers (3)

dev-eloper
dev-eloper

Reputation: 110

Map m = new groovy.json.JsonSlurper().parseText(json)
m.book.each{println it}

This is enough.

Upvotes: 1

Rao
Rao

Reputation: 21359

You can use Script Assertion for the same REST Request test step which can avoid another additional groovy step.

Script Assertion

assert context.response, 'Response is empty or null'

def json = new groovy.json.JsonSlurper().parseText(context.response)
log.info json.book

The above logs all the book details.

You may also use index to show a particular book details such as show book at 0 index.

log.info json.book[0]

It is also find certain book based on some filter. For instance, find a book whose description is Grammer.

log.info json.book.find {it.description == 'Grammer'}

Upvotes: 1

avidCoder
avidCoder

Reputation: 490

Finally, after so much effort. I got the solution and tried it with Map and List.

Object inputJSON = slurper.parseText(response)

def countBook = inputJSON.book.size()

for(int i=0; i<countBook; i++) {
Map result = (Map) inputJSON
List bookNode = result.get("book")
log.info bookNode[i]    

}

Upvotes: 0

Related Questions