How to count the length of json returned using Postman?
var body = JSON.parse(responseBody);
tests["Count: " + Object.keys(body.items).length] = true;
I suppose postman return json and might not always need to parse it, You then count the length of your "items" using https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Postman - How to count occurrences of a specific object in a JSON response
It is a rather specific solution but I hope it helps. The description is added as comments:
// Convert the response body to a JSON object
var jsonData = pm.response.json()
// Create a count variable which will be increased by 1 everytime IsArchived occurs
var count = 0;
function countIsArchived() {
// Loop through the FieldGroupsArray
_.each(jsonData.FieldGroups, (fieldGroupsArray) => {
// Loop through the FieldDefinitionsArray
_.each(fieldGroupsArray.FieldDefinitions, (fieldDefinitionsArray) => {
// Check if IsArchived exists
if(fieldDefinitionsArray.IsArchived) {
// Increase count by 1
count++;
}
});
});
// IF you want it:
// Check if IsArchived exists on the top level of the JSON response and increase count
if(jsonData.IsArchived) {
count++;
}
// IF you want it:
// Create a Postman environment variable and assign the value of count to it
pm.environment.set("count", count);
}
Additional info:
The ,
after the following object is not needed. It invalidates the JSON:
{
"Id": 33,
"DisplayName": "Long Description",
"IsArchived": false
}, <--
How to count number of values in array?
You could take a dynamic apporach and hand over the key of the object where you like to count a certain inner key.
function count(object, key, subKey) { const noObject = o => !o || typeof o !== 'object';
function subCount(object) { if (noObject(object)) return 0; if (subKey in object) return 1; return Object.values(object).reduce((s, o) => s + subCount(o), 0); }
if (noObject(object)) return 0; if (key in object) return subCount(object[key]); return Object.values(object).reduce((s, o) => s + count(o, key, subKey), 0);}
var data = { data: [{ alpha: "a", beta: "b", delta: { cat: "dog" }, gamma: { sierra: { data: [{ type: "alphabet", id: "a" }, { type: "alphabet", id: "b" }] } } }] };
console.log(count(data, 'sierra', 'id')); // 2
How to verify array length for postman test
Not sure about the structure of your response body, but this should do it.
Happy to adapt it, once you've posted your complete response body.
const resBody = pm.response.json();
const numberOfSalesEmployees = resBody.companies[0].salesReps.length;
console.log("Number of sales employees:" + numberOfSalesEmployees);
for (var i = 0; i < numberOfSalesEmployees; i++){
console.log("Name of sales rep " + i + ": " + resBody.companies[0].salesReps[i].name);
}
pm.test("Number of sales employees is 4", function () {
pm.expect(numberOfSalesEmployees).to.eql(4);
});
how to count length of the JSON array element
Before going to answer read this Documentation once. Then you clearly understand the answer.
Try this It may work for you.
Object.keys(data.shareInfo[i]).length
Postman: JSON test for count giving error
If you want to check how many objects are in the fdArea
array you could use the Lodash _.each()
function in the Tests
tab, to log out the number to the console:
_.each(pm.response.json(), (arrItem) => {
console.log(arrItem.fdArea.length)
})
With a response
data set like this one:
[
{
"fdArea":[
{
"dAreaId":2,
"dArea":"Belgium",
"dPrefixCode":"BE"
},
{
"dAreaId":3,
"dArea":" Czech",
"dPrefixCode":"CZ"
},
{
"dAreaId":6,
"dArea":"France",
"dPrefixCode":"FR"
},
{
"dAreaId":4,
"dArea":" Germany",
"dPrefixCode":"DE"
},
{
"dAreaId":7,
"dArea":" Hungary",
"dPrefixCode":"HU"
},
{
"dAreaId":8,
"dArea":"Italy",
"dPrefixCode":"IT"
},
{
"dAreaId":9,
"dArea":"Netherlands",
"dPrefixCode":"NL"
},
{
"dAreaId":10,
"dArea":" Poland",
"dPrefixCode":"PL"
},
{
"dAreaId":12,
"dArea":"Slovakia",
"dPrefixCode":"SK"
},
{
"dAreaId":14,
"dArea":"South Africa",
"dPrefixCode":"ZAF"
},
{
"dAreaId":5,
"dArea":"Spain",
"dPrefixCode":"ES"
},
{
"dAreaId":11,
"dArea":"Sweden",
"dPrefixCode":"SE"
},
{
"dAreaId":1,
"dArea":" United Arab Emirates",
"dPrefixCode":"ARE"
},
{
"dAreaId":13,
"dArea":"United Kingdom",
"dPrefixCode":"UK"
}
]
}
]
It would return the number 14
in the Postman Console.
Postman JSON parse response body arrays inside arrays
Here I am giving my own suggestion for your problem with few lines of code. I am not sure, how are you going to use these values. I also don't know if the outer options array will always have 1 item or more. I have just tried to satisfy your questions.
Please ask/comment, if you have more doubts or I am wrong.
I have created a function getAllPostmanDataFrom(obj)
which takes object as parameter which is the value of data[count]
, gathers necessary info in other object postmanObj
and returns it to the caller.
function getAllPostmanDataFrom(obj) {
const item_id = obj.options[0].id;
const item_name = obj.options[0].name;
const svc_optn_optn_name = obj.options[0].options[1].name;
const svc_optn_optn_id = obj.options[0].options[1].id;
const postmanObj = {item_id, item_name, svc_optn_optn_id, svc_optn_optn_name}; // Return object
return postmanObj;
}
var data = [
{
"id": 20599,
"name": "Deliver",
"options": [
{
"id": 63775,
"name": "Item",
"dataType": "SelectMultiOption",
"required": false,
"options": [
{
"id": 426,
"name": "Towels"
},
{
"id": 427,
"name": "Toothbrush"
},
{
"id": 428,
"name": "Pillow"
}
]
}
]
}
]
var count = 0;
var obj = data[count];
var postmanObj = getAllPostmanDataFrom(obj);
//var {item_id, item_name, svc_optn_optn_id} = postmanObj;
console. log(postmanObj)
/*
console.log(item_id);
console.log(item_name);
console.log(svc_optn_optn_id);
console.log(svc_optn_optn_name);
*/
Finally, you can use values contained in postmanObj as follows:.
postman.setEnvironmentVariable("item_id", postmanObj.item_id);
postman.setEnvironmentVariable("item_name", postmanObj.item_name);
And so on.
Related Topics
Uploading Multiple Files Using Formdata()
How to Split Date and Time from the Datetime Variable in JavaScript
Whenever I Click Outside the Element It Should Close
Google Charts: Move Legend Position
How to Clear Location.State in React-Router on Page Reload
Array Push Is Overwriting the Existing Array
Parsing String as Json With Single Quotes
React Hooks Error: Hooks Can Only Be Called Inside the Body of a Function Component
Javascript: How to Read a Hand Held Barcode Scanner Best
Jquery Event to Trigger Action When a Div Is Made Visible
Datepicker Onchange Event Not Firing in Jquery
Rendering Empty Space in React
How to Reference Static Assets Within Vue JavaScript
Check Checkbox and Trigger Change Event JavaScript
How to Get Values of Checkbox in Node Js Using Ejs
React-Native React-Navigation Undefined Is Not an Object (Evaluating 'S.Value.Startswith')
How to Build Pdf File from Binary String Returned from a Web-Service Using JavaScript