DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Adding Two Hours in DataWeave: Mule 4
  • Pydantic: Simplifying Data Validation in Python
  • Hybrid Search Using Postgres DB
  • Modify JSON Data in Postgres and Hibernate 6

Trending

  • Emerging Data Architectures: The Future of Data Management
  • Medallion Architecture: Efficient Batch and Stream Processing Data Pipelines With Azure Databricks and Delta Lake
  • Why High-Performance AI/ML Is Essential in Modern Cybersecurity
  • Understanding and Mitigating IP Spoofing Attacks
  1. DZone
  2. Data Engineering
  3. Data
  4. How to Parse JSON Responses in Katalon Studio

How to Parse JSON Responses in Katalon Studio

This tutorial offers a few basic best practices for working with JSON strings in Katalon Studio. Explore a JSON response example and JsonSlurper.

By 
Oliver Howard user avatar
Oliver Howard
·
Nov. 08, 18 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
18.3K Views

Join the DZone community and get the full member experience.

Join For Free

A JSON Response Example

Suppose we have the following JSON response, and we want to parse and retrieve its data:

{
  "menu": {
    "id": "file",
    "tools": {
      "actions": [
        {
          "id": "new",
          "title": "New file"
        },
        {
          "id": "open",
          "title": "Open File"
        },
        {
          "id": "close",
          "title": "Close File"
        }
      ],
      "errors": []
    }
  }
}

JsonSlurper

We use this Groovy helper class to parse JSON strings. We need to create a new instance of JsonSlurper and call the JsonSlurper.parseText method. Sample code:

import groovy.json.JsonSlurper

String jsonString = '''{"menu": {
"id": "file",
"tools": {
"actions": [
{"id": "new", "title": "New File"},
{"id": "open", "title": "Open File"},
{"id": "close", "title": "Close File"}
],
"errors": []
}}}'''
JsonSlurper slurper = new JsonSlurper()
Map parsedJson = slurper.parseText(jsonString)
import groovy.json.JsonSlurper

String jsonString = '''{"menu": {
"id": "file",
"tools": {
"actions": [
{"id": "new", "title": "New File"},
{"id": "open", "title": "Open File"},
{"id": "close", "title": "Close File"}
],
"errors": []
}}}'''
JsonSlurper slurper = new JsonSlurper()
Map parsedJson = slurper.parseText(jsonString)

The parsed JSON response is now stored in a variable called parsedJson(in our case, it is the Map data structure, but sometimes it may be something else).

JsonSlurper also provides a couple of JsonSlurper.parse overloading methods which can be used if your JSON input is File, Reader, InputStream, URL other than String. For further information, please refer to the JsonSlurper documentation.

Get a Key Value

Let’s say you want to get a value of id from the JSON response above. JSON is a structured document, so you can get any element using its absolute path. See this example:

String idValue = parsedJson.menu.id
String idValue2 = parsedJson.get("menu").get("id")

As you can see, there are two ways how to get it. One is to access Map objects by using the dot notation (.). The other is to use get methods from Map, List and Set as you do in Java.

Basically, the parsedJson variable is a type of Map<String, Map<Object, Object». Then, to get inner Map, you call parsedJson.get(“menu”) – as “menu” is the String key. This method returns the inner Map, on which you can call other get methods until you reach your key.

Verify If a Key Is Present in JSON

If you want to verify if a selected key is present in a JSON response, you can use the similar code as below:

import com.kms.katalon.core.util.KeywordUtil

String getSelectedKey = parsedJson.menu.id

if(getSelectedKey == null) {
KeywordUtil.markFailed("Key is not present")
}
It is a simple check for null – if the given key is not found, null is returned. But there is one special case when this code won't work, that is, if key "id" has value null in your JSON. For such cases you should use more robust code:
boolean isKeyPresent = parsedJson.get("menu").keySet().contains("id")

if (!isKeyPresent) {
KeywordUtil.markFailed("Key is not present")
}

You get all the keys from the “menu” object and then check if it contains the key you look for.

Get an Array Element

Your JSON response may also contain arrays. Like any array in Java or Groovy, you can access an array element using arrayName[index].

For example, we can get the “title” value of the first object in the “actions” array as below:

String idValue = parsedJson.menu.tools.actions[0].title
String idValue2 = parsedJson.get("menu").get("tools").get("actions").get(0).get("title")

In this example, we access the item with the index of 0, the first item in the array (the index is zero-based).

Get an Array Element Based on Some Condition

A more usual case is when you want to get the exact array element based on some specific condition. For example, you get the “title” value of an object whose “id” is “Open”. You can do this as below:

def array1 = parsedJson.menu.tools.actions

String onlickValue1 = ""

for(def member : array1) {
if(member.id == 'Open') {
onlickValue1 = member.title
break
}
}

I used the for-each loop in this case. This loop checks every item in the array array1 until the condition is met. If so, onlickValue1 is assigned to the item’s title.

JSON Data Types

The JSON format supports a few data types such as String, number, Boolean, and null. If you are not sure what the data type is, you can just use the keyword def.

def myVar = 'get value from json here'.

A rule of thumb is that a String value is enclosed in quotes, numbers unquoted (floating point may be present as well) and Boolean true or false. But initializing a variable using def is always a good choice when you are not sure about its type.

Conclusion

This tutorial offers a few basic best practices for working with JSON strings in Katalon Studio. JSON is the most common format returned from API/Web Services. When you perform API testing, you likely have to deal with JSON responses. Hopefully, these basic best practices are useful for your API testing.

JSON Katalon Studio Data Types Data structure

Published at DZone with permission of Oliver Howard. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Adding Two Hours in DataWeave: Mule 4
  • Pydantic: Simplifying Data Validation in Python
  • Hybrid Search Using Postgres DB
  • Modify JSON Data in Postgres and Hibernate 6

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!