Parse values in a JSON response array in Postman - javascript

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"]);

Related

Values not being sent in POST request to API (Postman + Strapi)

Im trying to POST an entry to Strapi through Postman. I have three fields in my endpoint, which are boxname + boxlocation + boxnumber. Two first are string and the last is integer. But for some reason my values doesnt get posted, they all turn up as null.
Any idea why? I ended up using Postman to try, because my Javascript wouldn't work either:
async function pushToStrapi(token, boxname, boxlocation, ownerid) {
var xhr = new XMLHttpRequest();
var url = "http://localhost:1337/boxes";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
}
};
var data = JSON.stringify({"boxname": ""+boxname+"", "boxlocation": ""+boxlocation+"" }});
xhr.send(data);
}
Theres a syntax error. Change:
var data = JSON.stringify({"boxname": ""+boxname+"", "boxlocation": ""+boxlocation+"" }});
To:
var data = JSON.stringify({"boxname": ""+boxname+"", "boxlocation": ""+boxlocation+"" });
If you prefer to use shorthand, you can do something like this:
var data = JSON.stringify({boxname, boxlocation});
You can't do this kind of request.
You will have to click on "body" then select the "raw" format and choose "JSON" in the format drop down.
Then in write your JSON object w/ your key values.
You can not send params in query parameters.
I have had this issue too, I'm learning Strapi, and in my case I was sending the ID in the JSON Object, wich is managed by Strapi, then I removed the ID (autoincremental value) and send only the data. In your example I see that you don't send the ID field, but this point maybe can help you or others who read.
This is my request:
{
"post_name": "raw postman post",
"post_description":"raw postman post",
"post_content": "raw postman post",
"post_category": 1 }
And this is the response that worked:
{
"id": 9,
"post_name": "raw postman post",
"post_description": "raw postman post",
"post_content": "raw postman post",
"post_category": {
"id": 1,
"category_name": "Climate",
"category_desc": "Climate",
"published_at": "2020-10-16T11:37:11.931Z",
"created_at": "2020-10-16T11:35:01.418Z",
"updated_at": "2020-10-16T11:37:11.950Z"
},
"published_at": "2020-10-22T11:35:59.714Z",
"created_at": "2020-10-22T11:35:59.722Z",
"updated_at": "2020-10-22T11:35:59.731Z"}

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

I am not get value which is sent in request body in specific json format

I need help in my one issue. I have write the program in that I am use map in node.js.
I am testing this program using postman by sending JSON structure, however I am not get specific value in console which I am printing.
Please see below code .
async CreateProduceMVPRateAsset(data, callback) {
// Create a new file system based wallet for managing identities.
var ProducePRICE = {};
var MVPRATE = new Map();
var MVPPRICE =[];
var MVPPRICE_BS ={};
var MVPPRICE_LB ={};
var PRODUCENAME = data.PRODUCE
console.log('PRODUCENAME', PRODUCENAME);
var COUNTRY = data.COUNTRY;
console.log('COUNTRY', COUNTRY);
var STATE = data.STATE;
console.log('STATE', STATE);
MVPRATES = data.MVPRATES;
console.log('MVPRATERATE', MVPRATES); // not getting value of MVPRATES from request body
}
JSON structure which is sending using POSTMAN
{
"username": "admin2",
"PRODUCE": "Apple",
"STATE": "MI",
"COUNTRY": "US",
"MVPRATES": {
"fuji": {
"VARIETY": "fuji",
"RATE": [
{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}
]
},
"gala": {
"VARIETY": "gala",
"RATE": [
{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}
]
}
}
}
output
Any help very appreciable
Thanks
Abhijeet
That's how logs will show up for the non-primitive type of data. Try stringifying the response like:
MVPRATES = data.MVPRATES;
console.log('MVPRATERATE', JSON.stringify(MVPRATES));
This will help you in printing actual values to the logs. A better approach will be to use a logging module like winston and configure all such things and many more.
Sorry to waste you all time I think I miss the var in front of MVPRATES. It should be
var MVPRATES = data.MVPRATES;

Check if JSON object exist (Postman)

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)

Accessing data from json in Angularjs

I have a JSON object Like this-
[
{
"user": "A220",
"shorttext": "shanghai",
"reportedBy": "S,A",
"questions": "
[{\"question\":\"Q1\",\"is_mand\":\"0\",\"type\":\"text\",\"answer\":\"w\",\"ansYesOrNo\":false,\"ansDetails\":\"\"},{\"question\":\"Q2\",\"is_mand\":\"0\",\"type\":\"text\",\"answer\":\"ed\",\"ansYesOrNo\":false,\"ansDetails\":\"\"}]",
"notifno": "20143995",
"error": "",
"createdOn": "2015-09-09 13:08:36",
"Id": 0,
"$$hashKey": "object:89"
}
]
I need to access the 1st question of questions.Please i am not able to access it like this alert(obj.questions[0].question);
Here is a jsFiddle Link-LINK to Fiddle
The main problem is that the questions array inside the object, It is not an array. Is a Array convert to string, you must parse the questions to get the respective Json object with the data.
Here is your fiddle updated: http://jsfiddle.net/marduke182/w02ck9uw/1/
And the part of code important:
var questonObj = JSON.parse($scope.a[0].questions);
Use fromJson method this way:
angular.fromJson(a[0].questions)[0].question

Categories