Check if JSON object exist (Postman) - javascript

I am trying to write a test in Postman to check if JSON keys are present in the response I received from the server.
The response:
{
"Result": 0,
"ResponseStatus": {
"ErrorCode": null,
"Message": null,
"StackTrace": null,
"Errors": null
},
"ResponseHeader": {
"Succeeded": true,
"Errors": null
},
"SessionId": "XXX-XXX-XXX"
}
I want to check "Results, Errorcode, Message,Succeeded" etc..
Thanks!

You could check the response scheme using:
var jsonData = JSON.parse(responseBody);
tests['response json contain Results'] = _.has(jsonData, 'Results');

According to your response body that you get, You can write simple test script for request under test section.
You need to parse your json response first. The script will look like:
var jsonData = JSON.parse(responseBody);
tests["Succeeded with value true"] = jsonData.ResponseHeader.Succeeded === true;
similarly you can write tests for other checks.For sessionId I would suggest you to check it with sessionId where it gets generated(store it in environment and check with it in this request)

Related

Cannot access JSON Properties within an HTTP POST Response

I am calling an HTTP POST Request, the response is JSON data.
POST Request:
const postXHR = new XMLHttpRequest();
postXHR.open('POST', postOptions);
postXHR.setRequestHeader("Accept", "text/json");
postXHR.setRequestHeader("Content-Type", "text/json");
postXHR.onreadystatechange = function() {
const response = postXHR.response;
if (response.response) {
console.log(postXHR.status);
}
createNewOptionValues(response);
}
postXHR.send('{"optionName":"optionName46", "platformName":"platformName46","dotDigitalId":3,"googleId":4}');
POST Response/JSON Data:
{
"data": {
"rooftopGoogleOptionId": 99,
"googleId": 4,
"dotDigitalId": 3,
"optionName": "optionName46",
"optionValue": null,
"platformName": "platformName46",
"googleAccount": null,
"dotDigitalAccount": null,
"updatedBy": null,
"updatedAt": null,
"createdBy": "root",
},
"status": 201,
"message": "success"
}
The createNewOptionValue function should log the value of a property within the response.
function createNewOptionValues(obj){
console.log(obj.googleId);
console.log(obj['googleId']);
}
Yet, the output is undefined, when using console.log(obj), the response does show.
When you receive a response, it is in "text" format (in most of the cases)
So you need to pass that response to JSON.parse for accessing it as a JSON Object.
Adding just 1 line in your createNewOptionValues function will make it work. Also, you need to access obj.data.googleId instead of accessing obj.googleId
function createNewOptionValues(obj){
obj = JSON.parse(obj)
console.log(obj.data.googleId);
console.log(obj.data['googleId']);
}

Parse values in a JSON response array in Postman

I'm trying to parse the value of "id" from the JSON body response to include in an environmental variable in Postman with no success. Here is an example of the Body response.
"payload": {
"transaction": {
"amount": "1.00",
"id": "114255633",
"type": "AUTH",
"result": "APPROVED",
"card": "XXXXXXXXXXXX1111",
"authorization-code": "TAS977",
}
}
and here is my script in postman
var jsonData = JSON.parse(responseBody);
var id = jsonData.payload[0].transaction.id;
postman.setEnvironmentVariable("id", id);
Any help would be appreciated. I think my error is in the way the value I'm looking to get is nested inside an array.
postman provides inbuild method to retrieve json object you don't have to parse it:
Also use the new pm api instead postman
pm.environment.set("id", pm.response.json().payload.transaction.id);
If I am not wrong..This should work
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("id", jsonData["payload"]["transaction"]["id"]);

How to access JS Object value in nestted object?

I am having trouble accessing the data in this JS Object. I can get this data by accessing data.queryParams. But if I try to drill lower, I get undefined. Below is what shows up if I do a JSON.stringify(data.queryParams). I've tried data.queryParams.attributes, data.queryParams[0], data.queryParams.handle, etc. And I get undefined for all of them.
console.log(data)
Object {
"hostname": "127.0.0.1",
"path": null,
"queryParams": Object {
"{\"attributes\":[{\"handle\":\"email\",\"name\":\"Email\",\"value\":\"test#test.com\"},{\"handle\":\"fname\",\"name\":\"First Name\",\"value\":\"Luke\"},{\"handle\":\"lname\",\"name\":\"Last Name\",\"value\":\"Skywalker\"},{\"handle\":\"zip\",\"name\":\"Postal Code\",\"value\":\"73067-9895\"},{\"handle\":\"uuid\",\"name\":\"Unique Identifier\",\"value\":\"XXXXXXXXXXXX\"}],\"status\":[{\"group\":\"penguins\",\"subgroups\":[\"King penguins\"],\"verified\":true}]}": "",
},
"scheme": "exp",
}
console.log(data.queryParams)
Object {
"{\"attributes\":[{\"handle\":\"email\",\"name\":\"Email\",\"value\":\"test#test.com\"},{\"handle\":\"fname\",\"name\":\"First Name\",\"value\":\"Luke\"},{\"handle\":\"lname\",\"name\":\"Last Name\",\"value\":\"Skywalker\"},{\"handle\":\"zip\",\"name\":\"Postal Code\",\"value\":\"73067-9895\"},{\"handle\":\"uuid\",\"name\":\"Unique Identifier\",\"value\":\"42e97018b6604fe491b82b629ad65c23\"}],\"status\":[{\"group\":\"penguins\",\"subgroups\":[\"King penguins\"],\"verified\":true}]}": "",
}
i think something wrong with your response, your data is set as key of the Object.
const obj = {
"hostname": "127.0.0.1",
"path": null,
"queryParams": {
// below is your data as key
"{\"attributes\":[{\"handle\":\"email\",\"name\":\"Email\",\"value\":\"test#test.com\"},{\"handle\":\"fname\",\"name\":\"First Name\",\"value\":\"Luke\"},{\"handle\":\"lname\",\"name\":\"Last Name\",\"value\":\"Skywalker\"},{\"handle\":\"zip\",\"name\":\"Postal Code\",\"value\":\"73067-9895\"},{\"handle\":\"uuid\",\"name\":\"Unique Identifier\",\"value\":\"XXXXXXXXXXXX\"}],\"status\":[{\"group\":\"penguins\",\"subgroups\":[\"King penguins\"],\"verified\":true}]}": "",
},
"scheme": "exp",
};
let value = Object.keys(obj.queryParams)[0]; // <-- get your data
value = JSON.parse(value); // <-- set to JSON
console.log(value.attributes) // <-- test log attributes
but better if you can fix the response
Try with JSON.parse to convert your JSON string to an object, then you can access your data
let attributes = JSON.parse(data.queryParams).attributes;
console.log(attributes)

Ignore Hyphen in Javascript (Postman)

Building a RestAPI with Postman.
I have some JSON data:
{
"progress-update": {
"#type": "parallel-progress",
"job": {
"#href": "/api/space/job-management/jobs/4691268"
},
"taskId": 4691268,
"jobName": "Compare Config-4691268",
"state": "DONE",
"status": "SUCCESS",
"percentage": 100,
"data": "<![CDATA[Total requests: 3<br>InSync count : 3<br>OutOfSync count : 0<br>]]>",
"subTask": [
{
I want to pull the "state" value into an environment Variable that i can then use to determine wether to continue on to the next request or wait until the state is DONE.
The problem i'm running into is "progress-update": has a hyphen in it, causing my script to not recognize it.
var jsonData = JSON.parse(responseBody);
pm.environment.set("JobStatus", jsonData.progress-update.state);
Postman returns the following error:
There was an error in evaluating the test script: ReferenceError:
update is not defined
You should be able to access your JSON data with
var jsonData = JSON.parse(responseBody);
pm.environment.set("JobStatus", jsonData['progress-update'].state);
using the object bracket notation

Creating an asana task with asana api gives invalid identifier error

MY Payload looks like this.
var data={
"workspace":"1234",
"name": task_name ,
"notes":striped_msg ,
"memberships":[
{
"project":678,
"section":111
},
{
"project":1230
}
],
"custom_fields":{
"303093523672299":"303093523672300"
},
"due_on":string_date
}
sending the payload like this.
var status = await asanaService.addTask(JSON.stringify(data))
Getting the following error in response
{"errors":[{"message":"Could not interpret {\"workspace\":"1234",\"name\":\"rohit as an identifier in {\"workspace\":"1234",\"name\":\"rohit.one [ Mysql cpu ]\",\"notes\":..............","help":"For more information on API status codes and how to handle them, read the docs on errors: https://asana.com/developers/documentation/getting-started/errors"}]}
I was Missing the JSON header during post

Categories