cancel
Showing results for 
Search instead for 
Did you mean: 

Groovy best practices - How to set the root node when extracting data from a response?

SOLVED
Highlighted
Contributor

Groovy best practices - How to set the root node when extracting data from a response?

See this code:

 

def jobDate = context.expand( '${GetJobInfo#Response#$[\'jobData\'][0][\'jobDate\']}' )

 


I see this kind of code too many times in a codebase. For example, it will be repeated for each variable inside jobData json object. This is an eyesore for the reader and makes it harder to understand the code.

Is there a way to set the root node in context.expand(...)? So, I could set the root node as jobData[0] and refer to all the elements inside it without using the full path.

I guess I could also create a variable rootPath and keep changing it as needed. Would that work?

1 ACCEPTED SOLUTION

Accepted Solutions
Community Leader

Re: Groovy best practices - How to set the root node when extracting data from a response?

@rajs2020 : If it is an array, then instead of using context of expand you can use jsonSlurper to get the value from the array by iterating over each element. Refer below link for documentation

 

json-slurper 


Click "Accept as Solution" if my answer has helped,
Remember to give "Kudos" 🙂 ↓↓↓↓↓



Thanks and Regards,
Himanshu Tayal

View solution in original post

3 REPLIES 3
Community Leader

Re: Groovy best practices - How to set the root node when extracting data from a response?

@rajs2020 : If it is an array, then instead of using context of expand you can use jsonSlurper to get the value from the array by iterating over each element. Refer below link for documentation

 

json-slurper 


Click "Accept as Solution" if my answer has helped,
Remember to give "Kudos" 🙂 ↓↓↓↓↓



Thanks and Regards,
Himanshu Tayal

View solution in original post

Highlighted
Contributor

Re: Groovy best practices - How to set the root node when extracting data from a response?

Thanks. Is it okay to use JsonSlurper for a project at work? I wonder if this library is used widely in the software industry and specifically inside ReadyAPI. That would make me more confident about using it. I don't want a new library to become a hindrance because its hard to use, has no active maintainers etc.

Highlighted
Community Manager

Re: Groovy best practices - How to set the root node when extracting data from a response?

Thanks, Himanshu for suggesting this!

 

@rajs2020 Yes, using the JsonSlurper class is safe. It's not from an external library. It is part of the standard goovy package (groovy.json). This package is included in the current stable version - version 3, we are using it in ReadyAPI. And, it will be part of version 4 as well. 


Sonya Mihaljova
Community and Education Specialist

Did my reply answer your question? Give Kudos or Accept it as a Solution to help others. ⬇️⬇️⬇️
New Here?
Join us and watch the welcome video:
Announcements
Top Kudoed Authors