How do i get a specific data from responseBody on postman - json

I'm trying to set an environment variable using the following:
var data = JSON.parse(responseBody);
pm.environment.set("petId", data.id);
And this is what is in my response:
{
"id": 9222999990497629102,
"category": {
"id": 0,
"name": "dog"
},
"name": "Brutus",
"photoUrls": [
"http://placeimg.com/640/480"
],
"tags": [
{
"id": 0,
"name": "string"
}
],
"status": "available"
}
But somehow my environment looks like this:
"petId": "9222999990497629000"
I don't where from where I'm getting these last zeros on my variable.

pm.environment.set("petId", JSON.parse(pm.response.text().replace(/"id":[\s]*([\d]+),/,'"id":"$1",')).id);
As the id is a big int greator than MAX_SAFE_Integer , the response will be rounded when parsed as JSON. It is a javascript behavior.
You can enclose it with double quotes. After that extract that id.
now if you want to convert id to number use BigInt
let id = JSON.parse(pm.response.text().replace(/"id":[\s]*([\d]+),/,'"id":"$1",')).id
id = BigInt(id)
console.log(id)
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

Related

Json Extractor in JMeter

I am using JSON extractor in JMeter. Below is my Response Body. I am using the Json path expression to capture the value, which is working fine.
Apart from the above condition, I need to add one more condition.
If the "travelID" length is equal to 33, then only I need to get the BoundID.
Example : AAA-AB1234-AAABBB-2022-11-10-1111
Total length or count of the above travelID is 33, but sometime I used to get 31,32 also but I need to capture the Bound ID only when the length is 33. Is that feasible ? Please help on the same
PFB sample response body.
{
"data": {
"RenewalDetails": [
{
"ExpiryDetails": {
"duration": "xxxxx",
"destination": "XXX",
"from": "XXX",
"value": 2,
"segments": [
{
"valudeid": "xxx-xx6262-xxxyyy-1111-11-11-1111"
}
]
},
"Itemdetails": [
{
"BoundId": "xxx-1-xxx1-111111111111-1",
"isexpired": true,
"FamilyCode": "PREMIUM",
"availabilityDetails": [
{
"travelID": "AAA-AB1234-AAABBB-2022-11-10-1111",
"quota": "X",
"scale": "XXX",
"class": "X"
}
]
}
]
}
]
},
"warnings": [
{
"code": "xxxx",
"detail": "xxxxxxxx",
"title": "xxxxxxxx"
}
]
}
I don't think it's possible with JSON Extractor, I would rather suggest going for JSR223 PostProcessor and the following Groovy code:
def BoundId = new groovy.json.JsonSlurper().parse(prev.getResponseData())
.data.RenewalDetails[0].Itemdetails.find { itemDetail ->
itemDetail.availabilityDetails[0].travelID.length() == 33
}?.BoundId
vars.put('BoundId', BoundId ?: 'Not Found')
You will be able to refer extracted value as ${BoundId} later on where required.

How to set 2 collection variables in postman using pre-request script if the id's in the response body have dependency?

I'm trying to set 2 collections variables in the postman using a pre-request script by picking the id's from response body. There are two id's namely id and subId, I need to set both the id's in the collection variables only if the id is linked to subId.
Need to get id and subId from below json response (there may be multiple records where id doesn't have subId value). Please help me to solve this.
{
"result": [
{
"id": 26,
"name": "Testing",
"code": "TST-012",
"branches": [
{
"emailId": null,
"country": {
"shortName": "Niu",
"currency": "New Zealand Dollar"
}
}
],
"subId": [
{
"id": 46,
"name": "qa",
"code": "qa"
}
]
},
{
"id": 27,
"name": "Testing",
"code": "TST-012",
"branches": [
{
"emailId": null,
"country": {
"shortName": "US",
"currency": "US Dollar"
}
}
],
"subId": null
}
]
}
Extract id that contains subId not null
const res = pm.response.json();
const matchEle = res.result.find(e => e.subId !== null);
pm.collectionVariables.set("id", matchEle.id); //26
Extract id inside subId
If get all id
const subIds = _.map(matchEle.subId, _.property("id"));
pm.collectionVariables.set("subIds", JSON.stringify(subIds)); //[46]
If only get first id
pm.collectionVariables.set("subId", matchEle.subId[0].id); //46

How to Check a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this.
{
"resultset": {
"violations": {
"hpd": [
{
"0": {
"ViolationID": "110971",
"BuildingID": "775548",
"RegistrationID": "500590",
"Boro": "STATEN ISLAND",
"HouseNumber": "275",
"LowHouseNumber": "275",
"HighHouseNumber": "275",
"StreetName": "RICHMOND AVENUE",
"StreetCode": "44750",
"Zip": "10302",
"Apartment": "",
"Story": "All Stories ",
"Block": "1036",
"Lot": "1",
"Class": "A",
"InspectionDate": "1997-04-11",
"OriginalCertifyByDate": "1997-08-15",
"OriginalCorrectByDate": "1997-08-08",
"NewCertifyByDate": "",
"NewCorrectByDate": "",
"CertifiedDate": "",
"OrderNumber": "772",
"NOVID": "3370",
"NOVDescription": "§ 27-2098 ADM CODE FILE WITH THIS DEPARTMENT A REGISTRATION STATEMENT FOR BUILDING. ",
"NOVIssuedDate": "1997-04-22",
"CurrentStatus": "VIOLATION CLOSED",
"CurrentStatusDate": "2015-03-10"
},
"count": "1"
}
]
}
},
"count": "1",
"total_page": 1,
"current_page": 1,
"limit": [
"0",
"1000"
],
"status": "success",
"error_code": "",
"message": ""
}
I am trying to test whether my response body has "ViolationID":"110971".
I tried the below code in postman:
var jsonData =JSON.parse(responseBody);
tests["Getting Violation Id"] = jsonData.resultset.violations.hpd[0].ViolationID === 110971;
Two issues I noticed in the provided data. The following suggestions might help you:
Add missing closing braces at the end.
Add missing 0 in the index like this: resultset.violations.hpd[0].0.ViolationID
If the hpd array always contains only 1 member, the test might be pretty straightforward:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationId = jsonBody.resultset.violations.hpd[0]["0"].ViolationID;
pm.expect(parseInt(violationId)).to.eql(110971);
})
However, if hpd array might contain more than one member, it gets a bit trickier. I would suggest mapping only ViolationID keys from nested objects:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationIds = jsonBody.resultset.violations.hpd.map(hpd => hpd["0"].ViolationID);
pm.expect(violationIds).to.contain('110971');
})

parsing nested json data - access directly to a member

I have json data like
data = {
"id":1,
"name":"abc",
"address": {
"items":[
"streetName":"cde",
"streetId":"SID"
]
}
}
How can i access directly to the streetName Value ?
Your json is actually invalid. If you have control over the json generation, first change it to this:
data = {
"id": 1,
"name": "abc",
"address": {
"items": [{
"streetName": "cde",
"streetId": "SID"
}]
}
}
Notice the additional braces around streetName and streetId. Then, to access streetName, do this:
var streetName = data.address.items[0].streetName;

How do I give a where clause or condition to get a value in json response using rest asssured

I need to extract the value of id where name == 'abc'. How can I do that?
here is the example of response:
{
"Text": [
{
"id": "123",
"name": "ABC"
},
{
"id": "456",
"name": "XYZ"
},
{
"id": "789",
"name": "DEF"
}
]
}
So I need to extract the value of id where name =='ABC' should return me id value as 123.
I need to use jayway restassured.
Use GPath findAll feature
when().
get("/restapi").
then().
body("text.findAll{ it.name == 'ABC' }.id", hasItem("123"));