0% found this document useful (0 votes)
36 views9 pages

JSONPath Examples in Rest Assured

The document provides a comprehensive guide on using JSONPath in Rest Assured for querying JSON data in API tests. It includes various examples demonstrating how to extract single values, lists, nested values, and apply filters and conditions. The examples range from basic extraction to more complex queries involving aggregation and nested structures.

Uploaded by

sangee.prabha22
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views9 pages

JSONPath Examples in Rest Assured

The document provides a comprehensive guide on using JSONPath in Rest Assured for querying JSON data in API tests. It includes various examples demonstrating how to extract single values, lists, nested values, and apply filters and conditions. The examples range from basic extraction to more complex queries involving aggregation and nested structures.

Uploaded by

sangee.prabha22
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Examples based on JSONPath in Rest Assured

JSONPath is a syntax for querying JSON data, similar to XPath for XML. In the context of Rest
Assured, JSONPath is used to extract specific pieces of information from a JSON response. It
allows you to traverse the JSON structure, filter data, and retrieve the values you need for your
API tests.

JSON Path is a powerful way to query and extract specific data from JSON documents. In Rest
Assured, JSON Path is used to navigate and extract data from JSON responses efficiently. JSON
Path expressions are akin to XPath expressions used in XML documents.
Rest Assured provides a convenient way to apply JSONPath expressions to a JSON response. It
can be used to assert values, extract data for further use, or perform various other checks on
the response.
JSONPath Syntax Basics
• Root: $ refers to the root of the JSON.
• Dot Notation: Accesses child elements, e.g., $.[Link].
• Bracket Notation: Alternative to dot notation, useful for accessing keys with special
characters or spaces, e.g., $['store']['book'].
• Wildcards: * can be used to match any element, e.g., $..author (all authors).
• Array Indexing: Access specific elements of an array, e.g., $.[Link][0].
• Filters: [?(@.price < 10)] filters items based on a condition.

Example 1: Extracting a Single Value


Scenario: Mike wants to extract the firstName from a JSON response.
import [Link];
import [Link];
import static [Link];

public class SimpleJsonPathExample1 {


public static void main(String[] args) {
Response response = [Link]("[Link]
String firstName = from([Link]()).getString("firstName");
[Link]("First Name: " + firstName);
}
}
Example 2: Extracting a List of Values
Scenario: Mahii wants to extract all emails from a JSON response containing a list of users.
import [Link];
import [Link];
import static [Link];
import [Link];

public class SimpleJsonPathExample2 {


public static void main(String[] args) {
Response response = [Link]("[Link]
List<String> emails = from([Link]()).getList("email");
[Link]("Emails: " + emails);
}
}
Example 3: Extracting a Nested Value
Scenario: Sweta wants to extract the city from a nested address object in the JSON response.
import [Link];
import [Link];
import static [Link];

public class SimpleJsonPathExample3 {


public static void main(String[] args) {
Response response = [Link]("[Link]
String city = from([Link]()).getString("[Link]");
[Link]("City: " + city);
}
}
Example 4: Extracting Multiple Values Using a Loop
Scenario: Mike wants to extract all phone numbers from a list of users.
import [Link];
import [Link];
import static [Link];
import [Link];

public class SimpleJsonPathExample4 {


public static void main(String[] args) {
Response response = [Link]("[Link]
List<String> phoneNumbers = from([Link]()).getList("phone");
[Link](phone -> [Link]("Phone: " + phone));
}
}
Example 5: Extracting a Boolean Value
Scenario: Mahii wants to check if the isActive status of a user is true.
import [Link];
import [Link];
import static [Link];

public class SimpleJsonPathExample5 {


public static void main(String[] args) {
Response response = [Link]("[Link]
boolean isActive = from([Link]()).getBoolean("isActive");
[Link]("Is Active: " + isActive);
}
}
Example 6: Filtering Data
Scenario: Sweta wants to extract firstName of users whose age is greater than 30.
import [Link];
import [Link];
import static [Link];
import [Link];

public class ModerateJsonPathExample1 {


public static void main(String[] args) {
Response response = [Link]("[Link]
List<String> firstNames = from([Link]()).getList("findAll { [Link] > 30
}.firstName");
[Link]("First Names: " + firstNames);
}
}
Example 7: Extracting Data Based on Conditions
Scenario: Mike wants to get the email of the user whose username is "mike123".
import [Link];
import [Link];
import static [Link];

public class ModerateJsonPathExample2 {


public static void main(String[] args) {
Response response = [Link]("[Link]
String email = from([Link]()).getString("find { [Link] == 'mike123'
}.email");
[Link]("Email: " + email);
}
}
Example 8: Extracting Part of a Nested Object
Scenario: Mahii wants to extract the zipcode from the address of a user where the city is "New
York".
import [Link];
import [Link];
import static [Link];

public class ModerateJsonPathExample3 {


public static void main(String[] args) {
Response response = [Link]("[Link]
String zipcode = from([Link]()).getString("find { [Link] == 'New York'
}.[Link]");
[Link]("Zipcode: " + zipcode);
}
}
Example 9: Extracting Nested Arrays
Scenario: Sweta wants to extract the titles of all books owned by the user "sweta123".
import [Link];
import [Link];
import static [Link];
import [Link];
public class ModerateJsonPathExample4 {
public static void main(String[] args) {
Response response = [Link]("[Link]
List<String> titles = from([Link]()).getList("find { [Link] == 'sweta123'
}.[Link]");
[Link]("Book Titles: " + titles);
}
}
Example 10: Extracting Data with Specific Index
Scenario: Mike wants to get the firstName of the second user in the JSON array.
import [Link];
import [Link];
import static [Link];

public class ModerateJsonPathExample5 {


public static void main(String[] args) {
Response response = [Link]("[Link]
String firstName = from([Link]()).getString("[1].firstName");
[Link]("First Name of Second User: " + firstName);
}
}
Example 11: Using Regular Expressions
Scenario: Mahii wants to extract the email of users whose email domain is [Link].
import [Link];
import [Link];
import static [Link];
import [Link];
public class HardJsonPathExample1 {
public static void main(String[] args) {
Response response = [Link]("[Link]
List<String> emails = from([Link]()).getList("findAll { [Link] ==~
/.*@[Link]/ }.email");
[Link]("Emails: " + emails);
}
}
Example 12: Extracting Data from Deeply Nested Structures
Scenario: Sweta wants to get the price of a specific product from a deeply nested orders
structure.
import [Link];
import [Link];
import static [Link];

public class HardJsonPathExample2 {


public static void main(String[] args) {
Response response = [Link]("[Link]
double price = from([Link]()).getDouble("[Link] { [Link] == 123 }.[Link] {
[Link] == 'ProductA' }.price");
[Link]("Price of ProductA: " + price);
}
}
Example 13: Combining Multiple Conditions
Scenario: Mike wants to extract the username of users who are active and live in "California".
import [Link];
import [Link];
import static [Link];
import [Link];

public class HardJsonPathExample3 {


public static void main(String[] args) {
Response response = [Link]("[Link]
List<String> usernames = from([Link]()).getList("findAll { [Link] &&
[Link] == 'California' }.username");
[Link]("Usernames: " + usernames);
}
}
Example 14: Using Aggregation Functions
Scenario: Mahii wants to find the maximum age of users in the list.
import [Link];
import [Link];
import static [Link];

public class HardJsonPathExample4 {


public static void main(String[] args) {
Response response = [Link]("[Link]
int maxAge = from([Link]()).getInt("max { [Link] }");
[Link]("Maximum Age: " + maxAge);
}
}
Example 15: Extracting Data with Complex Path
Scenario: Sweta wants to extract all product names from orders where the totalAmount is
greater than 1000.
import [Link];
import [Link];
import static [Link];
import [Link];

public class HardJsonPathExample5 {


public static void main(String[] args) {
Response response = [Link]("[Link]
List<String> productNames = from([Link]()).getList("findAll { [Link] >
1000 }.[Link]()");
[Link]("Product Names: " + productNames);
}
}
These examples cover different complexities of using JSON Path in Java Rest Assured,
showcasing how to query JSON data ranging from simple value extraction to complex filtering
and aggregation.

Common questions

Powered by AI

Using JSONPath in Rest Assured for API testing presents several challenges and limitations, including handling complex and deeply nested JSON structures which might require lengthy and intricate JSONPath expressions, potentially leading to reduced readability and maintainability of test scripts. Additionally, JSONPath does not inherently support operations beyond querying, such as data modification, limiting its usage to strictly read operations. Handling JSON responses with dynamic keys or irregular structures can also pose difficulties, as JSONPath expects a consistent structure for queries. These challenges necessitate careful crafting of JSONPath queries and thorough understanding of JSON schemas for effective use .

Using filters in JSONPath expressions offers several advantages when working with JSON data in Rest Assured. Filters enable targeted extraction by allowing conditions to be applied directly to JSON data, thereby reducing the amount of data transferred and processed. This helps in focusing on relevant data rather than going through the entire JSON payload. For example, one can extract first names of users whose age is greater than 30 or find emails based on username conditions. Filters improve efficiency, readability, and precision in test scripts, leading to better maintenance and quicker debugging .

JSONPath facilitates complex data extraction and manipulation by abstracting the navigation through complex JSON structures, which would otherwise require explicit parsing and traversal logic via traditional methods in Java. JSONPath expressions allow concise querying of nested elements, filtering conditions, and aggregation functions directly within the expression syntax. This not only saves time but also reduces code complexity and potential errors by minimizing direct parser interactions. For example, extracting products based on conditions or navigating deeply nested structures becomes straightforward with JSONPath, enabling effective and efficient data handling within testing frameworks like Rest Assured .

JSONPath's use of logical conditions simplifies complex data extraction scenarios by enabling queries that integrate multiple criteria, thus providing a targeted approach to data retrieval. For example, extracting usernames of users who are active and reside in 'California' involves combining both the 'isActive' status and 'address.state' in a single query. This ability to concatenate logical conditions within JSONPath allows for the precise extraction of relevant data subsets without extra filtering or processing after extraction. Such functionality is crucial for scenarios requiring intersections of conditions or when dealing with large datasets .

JSONPath enhances the effectiveness of querying JSON data in automated API testing by providing a syntax similar to XPath for XML, which allows precise data extraction directly from JSON responses. This capability enables testers to assert values, extract necessary data for further use, and perform various checks efficiently. JSONPath allows for navigation through JSON structures, data filtering, and retrieval of specific values using familiar operations like dot notation, bracket notation, wildcards, array indexing, and filters .

JSONPath can be used in Rest Assured to extract and verify specific data points from a REST API response by applying JSONPath expressions to navigate the JSON structure and directly target the desired data. For instance, you can extract a user's email based on their username or verify a user's active status through logical conditions. JSONPath's range of syntax options, including dot notation, wildcards, and filters, allows testers to isolate data points and perform assertions directly within tests. This method enhances test accuracy and integrity by validating expected values against actual response data .

JSONPath can manage nested array data effectively by providing straightforward syntax to access elements within these arrays. For example, extracting all book titles owned by a user through a JSONPath query targeting nested arrays within a user object streamlines the process of dealing with multiple levels of data. JSONPath's support for array indexing, wildcards, and flattening of nested arrays facilitates specific target retrieval without manually traversing each array layer. This capability is essential for efficiently manipulating data structures where elements contain further lists or arrays .

Regular expressions can be effectively used within a JSONPath query in Rest Assured to match patterns within string data, such as email addresses or specific strings in JSON values. For instance, extracting emails of users whose email domain is 'example.com' utilizes regular expressions to identify and filter relevant email addresses from a JSON response containing multiple users. This allows efficient data extraction based on a specific pattern, enabling testers to verify or assert conditions related to string formats without manual pattern matching .

When using aggregation functions like finding the maximum age in JSONPath, it is crucial to ensure the correctness and context of the data. Considerations include the presence of complete and consistent data across elements to avoid skewed results, performance implications of operating on large JSON datasets, and ensuring that the field type is appropriate for aggregation (e.g., numeric field for maximum calculation). Aggregation must be meaningful concerning the application's logic, ensuring that the data aggregation aligns with user scenarios or business rules governing data usage .

JSONPath expressions are designed to query and extract data from JSON documents, similarly to how XPath is used for XML documents. Both allow traversal and search within hierarchical data structures using similar concepts such as root nodes, paths, wildcards, and conditional expressions. However, while XPath is intended for XML's tree-like structure with nodes and attributes, JSONPath caters to JSON's key-value pairs and arrays. JSONPath supports both dot and bracket notations for navigating JSON objects, akin to node paths in XML, though it does not have XML-specific constructs like attribute selectors. JSONPath is generally more straightforward due to JSON's simpler structure compared to XML .

You might also like