What is the best way to determine if a value exists in a JSON response?

I am currently creating a test in Postman to verify if a JSON response contains the 'RegressieMapTest' Label. Here is my script:

pm.test("Is the folder created correctly?", function(){
var jsonData = pm.response.json();
var objString = JSON.stringify(jsonData);
var obj =  JSON.parse(objString);

for (var i = 0; i < obj.Corsa.Data.length; i++){
    if (obj.Corsa.Data[i].Label == "RegressieMapTest"){
        console.log(obj.Corsa.Data[i].Label);
        pm.expect(obj.Corsa.Data.Label).to.eql("RegressieMapTest");
    }
}
pm.expect.fail();   
})

However, I am running into an issue as every time I execute this script, it seems to automatically go to pm.expect.fail(), even though 'RegressieMapTest' is present in the JSON response. The error message returned by Postman is:

Is the folder created correctly? | AssertionError: expect.fail()

Answer №1

pm.response.json() is equivalent to using JSON.parse, so there's no need to repeat the process

Additionally, consider utilizing the array.find method instead of manually looping through the array

pm.test("Is the folder created correctly?", function () {
    var jsonData = pm.response.json();

    pm.expect(obj.Corsa.Data.find(elem => elem.Label === "RegressieMapTest")).to.be.not.undefined

}

If the array contains an element with label "RegressieMapTest", it will return that data. Otherwise, it returns undefined. We are validating that it should not return undefined, indicating that the value exists.

Answer №2

Your code snippet pm.expect.fail(); is set to always run, but you actually want it to run only when the field is not found. To achieve this, consider adding a flag within your check block.

pm.test("Checking if the folder was created correctly", function(){
    var jsonData = pm.response.json();
    var objString = JSON.stringify(jsonData);
    var obj =  JSON.parse(objString);

    var isFound = false;
    for (var i = 0; i < obj.Corsa.Data.length; i++){
        if (obj.Corsa.Data[i].Label == "RegressieMapTest"){
            console.log(obj.Corsa.Data[i].Label);
            pm.expect(obj.Corsa.Data.Label).to.eql("RegressieMapTest");
            isFound = true;
        }
    }

    if (!isFound) {
        pm.expect.fail();
    }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refreshing the images array in the DOM using ajax technology

I have a webpage with various images scattered under a table, like in the example of homepage.htm: <table id="imagesTable"> <tr> <td> <img src="img1.png"> <div> <img src= ...

Creating a PHP table using JSON data without specifying column names in the array

I am struggling with the Yandex API, trying to retrieve data and create a table using PHP: {"data":[ {"dimensions":[{"name":"organic"}],"metrics":[s1v1,s1v2,s1v3,s1v4,s1v5,s1v6]}, {"dimensions":[{"name":"referral"}],"metrics":[s2v1,s2v2,s2v3,s2v4,s2v5,s2v ...

Unusual Behavior Causing Error: 'RangeError: Invalid time value'

Currently, I am developing a straightforward timestamp API using Express. Essentially, when a user inputs a date in 'regular' format, the API displays a JSON object with both the Unix format and the normal format. Below is the pertinent section o ...

Exploring VueJS: Sorting objects within an array

Currently, I am tackling a challenge in vue-js. In my codebase, there exists a data object known as items. I am iterating through these items and aiming to present a dropdown menu containing the list of products. My goal now is to showcase only those pro ...

When I try to run npm start with ReactJS, my localhost 3000 shows a blank page

After starting work on a new React app, I decided to name it the Covid-19 tracker. When I initially ran npm start, everything looked great with the h1 heading displaying properly. However, things took a turn after I installed some dependencies: npm install ...

The issue with Angularjs not displaying updated model data in ng-repeat view

I've encountered an issue with a "menu directive" not updating the items in the html view when the model changes. I'm using AngularJS with a for-each statement. Here is the minimal code snippet: The directive: export function SideNavbarDirectiv ...

Make sure to hold off on proceeding until the JavaScript function has fully executed and the PHP script

I am facing an issue with my registration form, which is displayed in an iFrame on my main window. After the user submits the form, a PHP script is supposed to insert the data into the database. The problem arises when I try to close the iFrame using a fun ...

Error in AngularJS v1.2.5 when using textarea with placeholder attribute in IE11

Having trouble with an Angular JS v1.2.5 form that is not functioning in IE11, despite working perfectly in Firefox, Chrome, and Safari. The issue seems to be related to using interpolation inside the placeholder attribute of a textarea. <body ng-con ...

Tips for patiently waiting for connection.connect

Looking for a way to validate mysql connections. What is the best approach to ensure the connection before proceeding in a function? function _testConnection( _host, _user, _password, _database) { let isConnected = false; let connection = mysql.cr ...

Having trouble interpreting JSON responses in AngularJS

How do I access the "teams" array from this JSON response using AngularJS? { "_links" : { "search" : { "href" : "http://localhost:8080/teams/search" } }, "_embedded" : { "teams" : [ { "name" : "Perspolis", "location" : ...

Changing the shading of an arc in d3.js: Tips and tricks

I've been attempting to create a gauge with a needle that changes the background color of the ring for the past few days. My goal is to dynamically update the colors of an arc within a gauge I developed in d3.js This is my current gauge setup with t ...

What is the best way to determine if an application has been installed on an Android device while browsing a website?

Let's set the scene: I've got a website that needs to use JavaScript to determine whether my app is already installed on the android device it's currently being used on. If the app is installed, the page will display a link (with a custom ...

What is the best way to implement the v-for loop in a Vue.js application?

I am currently working with a loop that contains four inputs. I am looking to assign separate id values from the loop to each of these inputs. How can I achieve this? click here for image click here for image While running a loop, I have only one input th ...

React onClick event not functioning properly

I am facing an issue with the 'onClick' event. Can anyone assist me with resolving this problem? I have eliminated unnecessary elements, but I am not receiving the expected message 'inside this was clicked'. import * as bootstrap fro ...

What is the process for incorporating Angular.js with a live messaging platform such as Pusher or PubNub?

Can Pusher or PubNub be implemented as an Angular service? Anyone have any examples of code for this kind of integration? ...

React Navigation - CSS file identified as "text/html" after introducing a dynamic route parameter (/userId)

Our customized stylesheet "styles.css" seems to be incorrectly identified with the MIME type "text/html", even though it is specified as: rel="stylesheet" type="text/css" This issue only arises when navigating to routes with a variable parameter such as ...

Struggling to interpret a JSON object from a log file using Java

Currently, I am in the process of learning Java. I have been given a task to work with a sample log file that contains key pairs and their corresponding values. The objective is to identify specific key pair values based on certain conditions within the li ...

Obtain the value of the selected item from a dropdown list that has been dynamically populated

Hello, I have successfully populated a list of items into an asp:DropDownList using JavaScript. Here is the code snippet: if (document.getElementById("<%=gdview.ClientID %>")!=null) { var rows = document.getElementById("<%=gdview.ClientI ...

The custom service is failing to load, in the simplest terms possible

After creating a dataService.j that contains the following: angular.module('dataService', []) .service('gameDataService', function() { var _gameData = { loggedIn: "false", gameJoined:"false", tableFu ...

When the onClick event is triggered, my intention is to dynamically insert a new

I'm having trouble adding a new row on each click, as my code keeps replacing the existing row. I attempted moving the if statement outside the addTable function, but it didn't work as expected. I've tried multiple solutions without succes ...