I am trying to set a postman environment variable based on a specific value in a response.
I'm unsure on code to use use to grab value.
I know I need to set the response as a variable which I have done as follows:
var response = JSON.parse(responseBody);
And I know I can use the following to set my environment variable:
postman.setEnvironmentVariable("category_ref",myVariableName);
Below is a snippet from my response:
{
"id": 45,
"name": "Accommodation",
"description": ""
},
{
"id": 46,
"name": "Accommodation (Engineering)",
"description": ""
},
I want to grab the "id" value based on "name" value which I will already know.
So an example being I want my code to give me the ID where "name" = "Accommodation"
Edit:
Changed made to original question following answers below.
My Tests code now looks like this:
//Ensure the API Test Category is present
var response = JSON.parse(responseBody);
tests["my test"] = responseBody.has("Accommodation");
//pass in id into variable for delete step
var requiredId = pm.response.json().find(function(element){
if (element.name == "Accommodation"){
return element.id;
}
});
stringId = JSON.stringify(requiredId);
pm.environment.set("category_ref",stringId);
console.log("my string "+stringId);
And my output to console looks like the following which is also the value that is being sent to the category_ref environment variable:
my string {"id":45,"name":"Accommodation","description":""}
The remaining problem is I don't want to return all the elements as it is doing above, I am wanting to return just "45" which is the id value where name = Accommodation.
Tests in Postman are noting but the JavaScript, so you can use Array.find() as follows,
Response Body:
[
{
"id": 45,
"name": "Accommodation",
"description": null
},
{
"id": 46,
"name": "Accommodation (Engineering)",
"description": null
}
]
Test window:
var matchedItem = pm.response.json().find(function(element) {
if (element.name == "Accommodation") {
return element;
}
});
console.log(matchedItem.id);
Related
Good morning everybody,
i'm working on a Slack Workflow and i exported the .json file to work on it manually.
In a step of the workflow, it opens a ticket on Jira and returns the Issue Key with this form:
"id": "d9332296-a027-4b51-a52b-d8d69f131374==issueKey"
I need to automatically add that ID to an url, i tried to pass it through % encoding but it doesn't work.
This is the code related to the specific action:
[
{
"id": "**d9332296-a027-4b51-a52b-d8d69f131374==issueKey**",
"type": "workflowtoken",
"property": "",
"data_type": "text"
},
{
"text": "\n\nLink to the issue: ",
"type": "text"
},
{
"url": "https://test.slack.com/channels/**%7B%7Bd9332296-a027-4b51-a52b-d8d69f131374%3D%3DissueKey%7D%7D**",
"text": "LINK",
"type": "link"
}
]
Do you know any easy way to store the value and pass it (like concatenate it with the url) or any other valid way to reach my goal?
Thank you very much,
P.
I tried to pass a json ID through % encoding to the url but it doesn't work.
Its hard to understand the context but the simplest way is to define some placeholder like JIRA_ISSUE_KEY and then replace it on every property that should get this issue key.
const dataObject = {
"id": "**d9332296-a027-4b51-a52b-d8d69f131374==JIRA_ISSUE_KEY",
"type": "workflowtoken",
"property": "",
"data_type": "text"
}
const injectVariables = (data, property, value) => {
const result = JSON.parse(JSON.stringify(data)); // silly copy
for(const key of Object.keys(result)){
if(result.hasOwnProperty(key)){
result[key] = result[key].replace(property, value);
}
}
return result;
};
const injectedData = injectVariables(dataObject, 'JIRA_ISSUE_KEY', 'project-123');
console.log(injectedData);
//I want to achieve "highestBid": "94628.41" displayed in A3 cell - the value of highestBid varies with time.
function response() {
var url = "https://api.zonda.exchange/rest/trading/ticker/BTC-PLN";
var response = UrlFetchApp.fetch("https://api.zonda.exchange/rest/trading/ticker/BTC-PLN");
var obj = { highestBid: "94628.41" };
type: "Fixed Multiple";
Status: "Active";
var result = Object.keys(obj).map((key) => [key, obj[key]]);
Logger.log(result);
SpreadsheetApp.getActiveSheet().getRange("A3").setValue(result);
}
The most important thing for you to do is to get the response body as a string using getContentText() and parse it as JSON using JSON.parse() so you can access the values easily in JavaScript following the structure of the returned data:
{
"status": "Ok",
"ticker": {
"market": {
"code": "BTC-PLN",
"first": { "currency": "BTC", "minOffer": "0.0000468", "scale": 8 },
"second": { "currency": "PLN", "minOffer": "5", "scale": 2 },
"amountPrecision": 8,
"pricePrecision": 2,
"ratePrecision": 2
},
"time": "1663191022379",
"highestBid": "94563.2",
"lowestAsk": "94846.78",
"rate": "94846.78",
"previousRate": "94566.21"
}
}
You should also make some other changes:
use const instead of var to treat values as immutable and you might also be interested in their scope
you should check for the response code using getResponseCode() as if the request fails (which it can for many reasons) you won't be able to access the data or get unexpected data returned. See HTTP status codes - Wikipedia.
For more details on what parsing means and how JSON and JavaScript are connected see this explanation.
Here now how you can set the value of highestBid in cell A3.
function response() {
const url = "https://api.zonda.exchange/rest/trading/ticker/BTC-PLN";
const response = UrlFetchApp.fetch(url);
if(response.getResponseCode != 200){
Logger.log(`The request failed with status code ${response.getResponseCode()}`)
} else {
// get the content of the response body as string (in UTF-8 encoding)
const responseStr = response.getContentText("UTF-8")
// the string is in JSON format so we can now parse it to make it accessible in javascript
const data = JSON.parse(responseStr);
// the hightest bid can now easily be obtained
const highestBid = data.ticker.highestBid;
Logger.log(`The highest bid is ${highestBid} until ${new Date(data.ticker.time).toLocaleString()}`)
// set value in cell A3
SpreadsheetApp.getActiveSheet().getRange("A3").setValue(highestBid);
}
}
By the way: Object.entries(result) returns the same result as var result = Object.keys(obj).map((key) => [key, obj[key]]);.
I have below scripts on Google Apps Script which will take in an JSON event.
I want the data in element "events", but it always return "Undefined" to me.
I'm guessing maybe it's because events is a JSON array and I can't directly use it in JS?
Here is my code:
function doPost(e) {
var msg = JSON.parse(JSON.stringify(e.postData.contents));
console.log(msg);
//log succesfully
console.log(msg.events);
//"Undefined"
}
If I try to log the elements in the events instead of the array events itself:
console.log(msg.events[0].replyToken);
//"TypeError: Cannot read property '0' of undefined at doPost(app:26:25)"
The result of msg will is in below:
{
"destination": "U656de3c6b48c8e0d44edda4fd3f05e06",
"events": [
{
"type": "message",
"message": {
"type": "text",
"id": "*********",
"text": "Hi"
},
"timestamp": 1642616050062,
"source": {
"type": "group",
"groupId": "***********",
"userId": "*************"
},
"replyToken": "************",
"mode": "active"
}
]
}
I've seen several similar problems for array in JS.
I tried them but all of them didn't work, please help me.
I guess the result your getting from your API as e.postData.contents is a JSON string.
In this case something like this:
var msg = JSON.parse(JSON.stringify(e.postData.contents));
would first try to turn something into a JSON string (JSON.stringify) and then converting it into a JavaScript object by JSON.parse. In other words the JSON.stringify is useless.
Try this instead:
var msg = JSON.parse(e.postData.contents);
If the value from "e.postData.contents" is already a string, you don't have to do JSON.stringify.
If you do JSON.parse(JSON.stringify(any string) it results in adding backslash" to the values. For example
let str = '{name: "John"}';
let myJSON = JSON.stringify(str);
myJSON = "{name: "John"}"
So, please make sure "e.postData.contents" is not a string.
I have nested JSON data which I am trying to parse using Javascript:
[
{
"fullUrl": "https://replacedURL.org/v/r4/fhir/MedicationRequest/83b6c511-8b78-4fe2-b484-346ddee61933",
"resource": {
"resourceType": "MedicationRequest",
"id": "83b6c511-8b78-4fe2-b484-346ddee61933",
"meta": {
"versionId": "4",
"lastUpdated": "2021-04-06T03:14:44.834-04:00",
"tag": [
{
"system": "https://smarthealthit.org/tags",
"code": "synthea-5-2019"
}
]
},
"status": "active",
"intent": "order",
"medicationCodeableConcept": {
"coding": [
{
"system": "http://www.nlm.nih.gov/research/umls/rxnorm",
"code": "316049",
"display": "Hydrochlorothiazide 25 MG"
}
],
"text": "Hydrochlorothiazide 25 MG"
},
"subject": {
"reference": "Patient/2cda5aad-e409-4070-9a15-e1c35c46ed5a"
},
How do I parse and print the names all of the medications into a div element with id="meds" under the JSON key "text"? What I am trying which is incomplete:
for (var i = 0; i < prop.length; i++) {
if(typeof obj[prop[i]] == 'undefined')
return defval;
obj = obj[prop[i]];
document.getElementById("meds").innerText = obj ++ ;
}
Not entirely sure what do to here. Help please?
Steps to populate the DIV element with a list of medications include
Obtain the JSON text which encodes the data object.
Parse the JSON (text) to create a JavaScript Object value
Use the object obtained to list medications in a DIV element.
Implementing step 1 depends on the choice of communication API used on the frontend (e.g. fetch, axios or jQuery) or if the JSON string is hardcoded in a script element inserted into page HTML when serving the page.
Step 2 may be included in step 1 by some APIs automatically, based on the mime type of response content, or by executing some kind of json method on the response object. If the front end gets the JSON as a text string it can call JSON.parse to convert the text into an object.
Step 3 doesn't appear to need parsing - the text property is of a nested object in an array entry. Standard shortcut notation to access its value may suffice. For example:
// assume dataArray is the result of parsing the JSON text.
// assume "meds" is the id of a DIV element
function listMeds( dataArray) {
const div = document.getElementById("meds");
dataArray
.map(entry => entry.resource.medicationCodeableConcept.text)
.map( med=> {
const span = document.createElement("span");
span.textContent = med;
const br = document.createElement("br");
div.appendChild(span);
div.appendChild( br);
})
}
Json is sitting on my localhost as: /data/:
{
"children": [
{
"name": "analytics",
"size": "1243"
},
{
"name": "math",
"size": "4343"
},
{
"name": "algebra",
"size": "1936"
},
{
"name": "calc",
"size": "3936"
},
{
"name": "geom",
"size": "2136"
},
{
"name": "Quant",
"size": "4136"
}
]
}
Here is how I am trying to access the json:
var interval = setInterval(function() {
$.getJSON("http://localhost:8080/dev_tests/d3/examples/data/flare2.json", function(json) {
$.each(json.children,function(i,name){
alert(json.children);
});
});
}, 3000);
The data comes in just fine. That is, when I run console.log(json) I can see the above json name/value txt pairs in firebug. However, before each name value pair I see the word Object. So for example instead of my log showing { name="analytics", size="1243"},.. it actually shows: [Object { name="analytics", size="1243"},... And that too is what my alert shows: [object Object] instead of name="analytics", size="1243".
Why is this and is there a way to get my json name/value pairs in text so that I can store as a javascript String?
Many thanks in advance.
jQuery does automatically decode the response when using jQuery.getJSON or specifying the response as JSON. If you want the plain response, use jQuery.ajax instead.
The O in JSON stands for "object." It's a way of serializing a JavaScript object to a string (and back). You seem to be relying on the conversion on one hand (referencing children) but not want to have the conversion done on the other hand. If you really want children to be a collection of strings in the format you describe, you should store it that way. If you really do want the object notation (and conversion to objects in the client), then you can simply use the properties of the object.
var interval = setInterval(function() {
$.getJSON("http://localhost:8080/dev_tests/d3/examples/data/flare2.json", function(json) {
$.each(json.children,function(i,item){
alert("name = " + item.name + ", size = " + item.size);
});
});
}, 3000);
Everything you've stated is normal behavior for both firebug and alert. You can't alert an object.
Here's example of how to loop the response within your $.get callback
http://jsfiddle.net/Y3N4S/
$.each(json.children, function(i, item){
$('body').append('<p>Name: '+item.name+' , Size: '+item.size+'</p>')
})
Well, working with Objects is the intend of "Javascript Object Notation".
Actually, your json is an Array of Objects.
{
"children": [ // <-- Array
{...},// <- Object
{...} // <- Object
]
}
You can access your key-value pairs this way: children[0].name
for (var i=0;i< children.length; ++){
console.log( children[i].name);
console.log( children[i].size);
}