I'm writing tests in POSTMAN against a POST API request by sending JSON body data of the following format:
"data": {
"name": "Amber Joseph",
"dob": "1988-10-13",
"addressLine1": "Ap #770-9459 Quis Av.",
"state": "WA",
"suburb": "Beverley",
"yesNo": false,
"balance": 423.00,
"club": [
"Dance",
"Sports"
],
"activities" : null
"libraryCard": {
"uid": "2d07d77c-8756-43d4-912f-238a2ff567fe"
}
}
I get Response for the request in similar format with some added details:
{
"status": "Success",
"message": "Created new 'Student' record",
"correlationCode": "Z848640-261354",
"type": {
"id": 51247,
"name": "Student",
"slug": "student",
"application": {
"name": "Willow University"
}
},
"data": {
"name": "Amber Joseph",
"dob": "1988-10-13",
"addressLine1": "Ap #770-9459 Quis Av.",
"state": "WA",
"suburb": "Beverley",
"yesNo": false,
"balance": 423.00,
"club": [
"Dance",
"Sports"
],
"libraryCard": {
"uid": "2d07d77c-8756-43d4-912f-238a2ff567fe",
"name": "11206"
}
}
Now i want to achieve two things here:
1. Verify each key in response body does not have null value. Please note i'm sending one key with value as null and it is not returned in response.
2. The value sent in request body for each key is value returned by same key in response body. For instance if "name" key has value "Amber Joseph" then response key "name" also returns "Amber Joseph". But i want to do it for each key. Also Keys can defer everytime for instance i might or might not send it with "name" key hence i need a generic solution that applies to whatever key value pairs i send.
I'm able to loop through by using:
let jsonData = pm.response.json();
let dKey = Object.keys(jsonData);
let dValue = Object.values(jsonData);
for(var i = 0; i < dV.length; i++ ){
pm.expect(dV[i]).to.not.eql(null);
}
But this does not check nested key value pair individually.I specially want to check each key value pair inside the "data" object. Any help would be appreciated.
Thanks
You can grab the JSON data from the request like this:
const requestJson = JSON.parse(pm.request.body.raw);
(This assumes you're using a RAW body in Postman.)
Then, you can compare the response's data fields with the original request's data fields:
const requestJson = JSON.parse(pm.request.body.raw);
const responseJson = pm.response.json();
for (const [reqKey, reqValue] of Object.entries(requestJson.data)) {
pm.expect(responseJson.data[reqKey]).to.eql(requestJson.data[reqKey]);
}
From there, you can add whatever checks you want to do on the rest of the response.
Related
I am having difficulty with a pulling some data from an API for a school project using Jquery.
If I use the following coinmaketcap API I get the following response
https://api.coinmarketcap.com/v1/ticker/bitcoin/
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "8854.92",
"price_btc": "1.0",
"24h_volume_usd": "6759730000.0",
"market_cap_usd": "150480289107",
"available_supply": "16993975.0",
"total_supply": "16993975.0",
"max_supply": "21000000.0",
"percent_change_1h": "-0.13",
"percent_change_24h": "0.12",
"percent_change_7d": "8.3",
"last_updated": "1524459272"
}
]
I get am able to get the symbol for Bitcoin and place it into a variable by using this code
> $.getJSON('https://api.coinmarketcap.com/v1/ticker/btc/',
> function(data){
> var symbol = (data[0].symbol)
> })
Once I have it I can place it in a div.
However when I use cryptocompare API I don't get anything back
https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC,&tsym=USD
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD', function(data){
var symbol = (data[0].Internal)
});
This is the response -
{
"Message": "Success",
"Type": 100,
"Data": [
{
"CoinInfo": {
"Id": "1182",
"Name": "BTC",
"FullName": "Bitcoin",
"Internal": "BTC",
"ImageUrl": "/media/19633/btc.png",
"Url": "/coins/btc/overview",
"Algorithm": "SHA256",
"ProofType": "PoW",
"NetHashesPerSecond": 27483320229.3688,
"BlockNumber": 518932,
"BlockTime": 600,
"BlockReward": 12.5,
"Type": 1,
"DocumentType": "Webpagecoinp"
},
"ConversionInfo": {
"Conversion": "direct",
"ConversionSymbol": "",
"CurrencyFrom": "BTC",
"CurrencyTo": "USD",
"Market": "CCCAGG",
"Supply": 16986575,
"TotalVolume24H": 380849.0498955779,
"SubBase": "5~",
"SubsNeeded": [
"5~CCCAGG~BTC~USD"
],
"RAW": [
"5~CCCAGG~BTC~USD~4~8875.23~1524460635~0.00477012~42.152119404000004~231254719~10820.885574747872~96327075.76938197~66326.58563159907~593473019.8524572~8823.46~8917.05~8804.2~8864.31~9065~8780.91~Bitfinex~7ffe9"
]
}
}
]
}
Why is the second piece of code not working? Please help!
The second API is returning an object (in JSON format), not an array - see how the first character is { and how it has keys and values? You need to access the appropriate property to get the value you want. [0] notation indicates you're trying to access the first element of the array, but the outer object is not an array in this situation.
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD',
function(data){
var symbol = data.Data[0].CoinInfo.Internal;
});
In both the cases, we are getting data in different form. So, To get the 'BTC' in variable .
for 1st case -> symbol = data[0] ['symbol']
for 2nd case -> symbol = data['Data'][0]['CoinInfo']['Internal']
one is an [array of JSON] while other is an [object having key 'Data' with array value].
Recently posted about looking through some json output from an API and got pointed to $getJSON and for loop issue
But im still really struggling and nothing I do works.
I have the following output from an API call :
{
"about": {
"name": "API",
"version": "2018.1.25.1",
"method": "get"
},
"sessions": {
"0": {
"sessionid": "c6fac08ad020cd10c377b77b81aac2ed19c08111",
"id": "121667",
"geolat": "51.9125118",
"geolon": "-2.1210269"
},
"1": {
"sessionid": "4f3da85c4905ee8c2a57ac48a22184b93fc2f680",
"id": "122589",
"chatstarted": "2018-02-24 23:41:51",
"geolat": "51.9125118",
"geolon": "-2.1210269"
}
},
"rescode": "200",
"executed": "nokeyfound-",
"queries": "5"
}
I just cant get it to loop through the "sessions" part of the Json.
The below "sort of works" but doesnt work at all, no errors, no output when loading it using $.getJSON (rather than just manually creating the object)
$.getJSON('https://api.php', function (Json) {
for (i in Json.sessions) {
alert(Json.sessions[i].id);
}
Surely it can't be that hard to just loop through only part of the data returned (the sessions) part.
What on earth am I doing wrong with this loop?
I just want to output sessionid on both rows. Seems impossible and been at this now for 9 hours straight no luck,
There has to be a way to just look at the sessions part and loop through the bits of that? surely? (0, 1 ,2 ,3 etc.. )
P.S I'm new to Javascript and JSON in particular and this is driving me insane.
Your result is not valid JSON because of a trailing , here:
"method": "get",
Always verify that the results you get back from a JSON request is valid before doing anything else.
Next, your syntax in the success handler is incorrect. You are missing a closing } for the for loop:
$.getJSON('https://api.php', function (Json) {
for (i in Json.sessions) {
alert(Json.sessions[i].id);
} // <-- You don't have this.
}
But, if we correct those things, then here's how we can iterate the results (keeping in mind that sessions is a key in the main object, but contains another object as its data:
var result = `{
"about": {
"name": "API",
"version": "2018.1.25.1",
"method": "get"
},
"sessions": {
"0": {
"sessionid": "c6fac08ad020cd10c377b77b81aac2ed19c08111",
"id": "121667",
"geolat": "51.9125118",
"geolon": "-2.1210269"
},
"1": {
"sessionid": "4f3da85c4905ee8c2a57ac48a22184b93fc2f680",
"cid": "122589",
"chatstarted": "2018-02-24 23:41:51",
"geolat": "51.9125118",
"geolon": "-2.1210269"
}
},
"rescode": "200",
"executed": "nokeyfound-",
"queries": "5"
}`;
resultObj = JSON.parse(result);
// Loop over the top-level object
for(var key in resultObj){
// Check the object key for the one we care about
if(key === "sessions"){
// Loop over the object stored in that key
for(var subKey in resultObj[key]){
// Access the sub-keys with an extra index:
console.log(resultObj[key][subKey]);
}
}
}
Or, to go directly to the sessions object:
var result = `{
"about": {
"name": "API",
"version": "2018.1.25.1",
"method": "get"
},
"sessions": {
"0": {
"sessionid": "c6fac08ad020cd10c377b77b81aac2ed19c08111",
"id": "121667",
"geolat": "51.9125118",
"geolon": "-2.1210269"
},
"1": {
"sessionid": "4f3da85c4905ee8c2a57ac48a22184b93fc2f680",
"cid": "122589",
"chatstarted": "2018-02-24 23:41:51",
"geolat": "51.9125118",
"geolon": "-2.1210269"
}
},
"rescode": "200",
"executed": "nokeyfound-",
"queries": "5"
}`;
resultObj = JSON.parse(result);
// Loop over the top-level object
for(var key in resultObj.sessions){
// Loop over the object stored in that key
for(var subKey in resultObj.sessions[key]){
// Access the sub-keys with an extra index:
console.log(subKey + " = " + resultObj.sessions[key][subKey]);
}
}
I wanted to check some combinations of validations for values I am getting from API request in postmanlike
if "tracked": "Yes" then analytics > "transitTime": 239 should be present.
The snippet of API response:
{
"status": 200,
"data": [{
"id": 107267,
"branchId": "22",
"status": "1",
"googleETA": "2018-02-01 20:44:51",
"runDate": "2018-01-29",
"runOfTheDay": "1",
"ATD": "2018-01-29 14:02",
"simCarrier": "Vodafone",
"pingStatus": "Ok",
"driverName": "test",
"shipperCompanyId": "007",
"ETA": "2018-01-30 12:31:00",
"locationSource": "sim",
"created_at": "2018-01-29 07:05:54",
"updated_at": "2018-01-29 12:35:40",
"tracked": "Yes",
"analytics": {
"loadingTime": 55.62,
"unloadingTime": 0,
"transitTime": 239
},
"trackingStatusAtClosure": {
"Origin": "No",
"Transit": "No",
"Destination": "No"
}
}]
}
This is a very basic check and I would advise against using it anywhere other than practising in a local environment.
pm.test("Basic Check", () => {
var jsonData = pm.response.json().data
for(i = 0; i < jsonData.length; i++) {
if(jsonData[i].tracked === 'Yes') {
pm.expect(jsonData[i].analytics.transitTime).to.not.be.null
} else {
console.log('Tracked does not equal Yes')
}
}
})
As your data only has one item in the data array you don't really need to add the for loop but I added it in for you so you can see that the same check would run if you have more than one item. If the tracked property is 'Yes' then the test is checking if analytics.transitTime not null. Like I said, its a basic check and it's not doing a great deal but hopefully that will give you the information you need to get started.
I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.
I am developing a website with front-end and back-end separated. I used jquery to send request and get the result as a json object:
{
"item": [
],
"shop": [
],
"user": [
{
"user_id": "9",
"full_name": "Minh Duc",
"email": "nguyenminhduc1803#gmail.com",
"fb_link": "https:\/\/www.facebook.com\/SieuNhan183",
"user_name": "Duc",
"password": "37cd769165eef9ba6ac6b4a0fdb7ef36",
"level": "0",
"admin": "0",
"dob": "1996-03-18",
"location": "Ho Chi Minh",
"user_image_url": null
}
]
}
Now i am finding a way to get the data from the object user. How can i do it with javascript?
Complementing #arcs answer, remember that in Javascript you can access members of an object using dot notation (data.user[0].user_id) or square brackets notation. This way:
data['user'][0]['user_id']
this is useful because you can have a 'class' array and then do things like:
['item', 'shop', 'user'].forEach((array) => processArray(data[array][0]));
then you can filter only some classes or do more advanced stuff
When you have the data (in example it's in data) use the dot notation to get the node with the user.
The user is an array, so use [] to access a single element, e.g. [0]
var data = {
"item": [
],
"shop": [
],
"user": [
{
"user_id": "9",
"full_name": "Minh Duc",
"email": "nguyenminhduc1803#gmail.com",
"fb_link": "https:\/\/www.facebook.com\/SieuNhan183",
"user_name": "Duc",
"password": "37cd769165eef9ba6ac6b4a0fdb7ef36",
"level": "0",
"admin": "0",
"dob": "1996-03-18",
"location": "Ho Chi Minh",
"user_image_url": null
}
]
}
console.log( data.user[0].user_id )
I prefer use square brackets like this :
$jsonObject["user"][0]["user_id"]
but you can use the dot like this :
data.user[0].user_id
is the same thing.
If you want check if property exist you can do it :
if(typeof $jsonObject["user"] !== 'undefined'){
//do domethings as typeof $jsonObject["user"][0]["user_id"]
}
If you want get property dinamically you can do it :
const strId = "id";
const strName = "name";
//get user_id
let user_id = $jsonObject[user][0]["user_" + strId ];
//get user_name
let user_name = $jsonObject[user][0]["user_" + strName];
but there isn't very pretty.