Effective API testing hinges on efficiently extracting and manipulating data from JSON responses. Postman, a popular API development platform, empowers users with JSONPath, a powerful query language specifically designed for navigating JSON structures.
If you are looking for an API tool to proceed with your app or API development, then you should strongly consider using Apidog - a one-stop solution to all your API problems.
If you wish to learn more about Apidog, click the button below!
This article delves into the world of Postman JSONPath, equipping you with the skills to unlock the full potential of your API interactions.
What is JSONPath?
JSON (JavaScript Object Notation) is a ubiquitous data format for exchanging information between APIs and applications. While its human-readable nature is a plus, complex JSON responses with nested objects and arrays can be daunting to navigate. This is where JSONPath comes in – a concise query language specifically designed to traverse and extract data from JSON structures.
JSONPath expressions resemble a roadmap, guiding you through the JSON hierarchy. Here's how it works:
Root Element
Root elements are represented by $
, it signifies the entire JSON document.
Child Nodes
Dot notation (.
) or bracket notation ([]
) is used to access child nodes.
- Dot notation is preferred for simple property names:
$.name
selects the "name" property of the root object. - Bracket notation is used for accessing properties with special characters or spaces:
$['full name']
targets the "full name" property.
Arrays
Square brackets with an index access specific elements: $.items[1]
selects the second element in the "items" array. Wildcards (*
) can be used to target all elements: $.products[*]
selects all elements in the "products" array.
Filters
Filters allow you to narrow down results based on conditions. For example, $..[?(@.price > 100)]
selects all objects within the JSON structure (denoted by ..
) where the "price" of property is greater than 100.
How Does Postman Work With JSONPath?
Test Scripts
JSONPath expressions can be embedded within Postman's test scripts to extract specific data from responses and perform assertions.
- Example:
pm.test("Status code is 200", () => pm.response.json().statusCode === 200);
- Example (with JSONPath):
pm.test("User ID is 123", () => pm.response.jsonPath("$.id") === 123);
Collections
JSONPath can be used within collection variables to dynamically define request parameters based on previous responses. This allows for building reusable and data-driven test cases.
- Example: Retrieve a user ID from a previous response and use it in a subsequent request:
pm.collectionVariables.set("userId", pm.response.jsonPath("$.id"));
Pre-request Scripts
JSONPath expressions can be used within pre-request scripts to manipulate data before sending a request.
- Example: Modify a request body based on specific values from a test environment variable:
pm.request.body.set("productId", pm.environment.variables.selectedProduct.id);
Examples of JSONPath Queries
These are some examples of JSONPath queries that can be implemented in the Postman pre-request section.

Example 1 - Conditional Logic with if function
Imagine a response with an "isActive" property for users. You want to extract their names, but only if they are active.
$.users[*].if(@.isActive, $.name, "Inactive")
This code uses the if
function. If the current user object has an "isActive" property set to true
, it extracts their name. Otherwise, it returns the string "Inactive".
Example 2 - Finding Minimum/Maximum Values
Let's say you have an "orders" array with an "amount" property for each order. You want to find the order with the minimum and maximum amount.
$..[?(@.type == "order")].amount.min() // Minimum amount
$..[?(@.type == "order")].amount.max() // Maximum amount
These queries leverage the min()
and max()
functions to identify the respective values in the "amount" property across all orders.
Example 3 - Flattening Nested Arrays
Postman doesn't natively support nested arrays. If you have a response with nested product categories, you might want to flatten them into a single list.
$.categories..[*] | flatten
This code utilizes the pipeline operator (|
) and the flatten
function. It traverses all nested elements within the "categories" structure and flattens them into a single-level array.
Example 4 - Working with Dates and Numbers
JSONPath can manipulate dates and numbers. Let's say you have a "createdAt" timestamp for users. You want to format it to a specific date format.
pm.response.json().users[*].createdAt.toString(pm.timestampFormat("YYYY-MM-DD")) // Assuming a pre-defined format function
This example combines JSONPath with a Postman scripting function (pm.timestampFormat
) to format the "createdAt" timestamp into the desired format (YYYY-MM-DD) within a pre-request script.
Example 5 - Combining JSONPath with Postman Variables
You can dynamically control JSONPath queries using Postman variables. Suppose you want to filter users based on a user ID stored in a variable.
$.users[?(@.id == pm.variables.get("selectedUserId"))]
Here, the pm.variables.get("selectedUserId")
retrieves the value stored in the "selectedUserId" variable and uses it within the JSONPath filter for dynamic user selection.
Apidog - Quickly Set Up Pre-Processor Scripts
Apidog is a comprehensive API development tool that can be a developer's perfect alternative to Postman.

With complete tools for the entire API lifecycle, developers can build, test, mock, and document APIs within just Apidog!

Setting Custom API Scripts Using Apidog

Apidog provides developers with code-generating features for custom scripts. You can get and set both environment and local variables.

You can also personalize the post-processor section of your API, specifying the JSONPath Expression and target object.
Creating New APIs with Apidog
Apidog empowers users with a high degree of design flexibility in the API creation process. This enables the development of APIs that precisely align with the functional requirements of your application or the specific needs of its intended users.

Begin by pressing the New API
button, as shown in the image above.

Having established the core functionality of your API, it is now essential to meticulously define its operational characteristics. This section outlines the key considerations involved in this process:
- HTTP Methods: Selection of the appropriate HTTP method (GET, POST, PUT, DELETE) is vital. These methods govern how users interact with and manipulate information within your API.
- API Endpoint: A unique web address (endpoint) must be chosen to serve as the access point for users to locate and interact with your API.
- Input Parameters: It is necessary to clearly specify any data elements that users can incorporate into the API address to retrieve specific responses.
- Functionality: A clear explanation is required to detail the precise actions and outcomes facilitated by your API.
To ensure you're building effective APIs, consider reviewing these helpful articles on REST API best practices.

Conclusion
Postman's integration of JSONPath unlocks a powerful and versatile tool for navigating and manipulating data within JSON responses. By mastering JSONPath expressions, you can efficiently extract specific values, filter results based on conditions, and even perform complex data transformations. This empowers you to streamline API testing workflows, gain deeper insights from responses, and build robust test cases that ensure the functionality and reliability of your APIs.
Furthermore, JSONPath's seamless integration with Postman's scripting capabilities opens doors for even more advanced use cases. You can dynamically control queries using variables, leverage functions for sophisticated data manipulation, and combine JSONPath with pre-request scripts or test scripts to automate complex tasks. By embracing the power of JSONPath in Postman, you elevate your API development process to a whole new level of efficiency and effectiveness.