Postman JSON parse response body arrays inside arrays - javascript

I have this JSON Response from API call
[
{
"id": 20599,
"name": "Deliver",
"options": [
{
"id": 63775,
"name": "Item",
"dataType": "SelectMultiOption",
"required": false,
"options": [
{
"id": 426,
"name": "Towels"
},
{
"id": 427,
"name": "Toothbrush"
},
{
"id": 428,
"name": "Pillow"
}
]
}
]
}
]
I am using this code to get the id of the service "Deliver"
var data = JSON.parse(responseBody);
var loop_count = 0
for (count = 0; count < data.length; count++)
{
if (data[count].name == "Deliver")
{
var job_id = data[count].id;
postman.setEnvironmentVariable("service_id", job_id);
}
}
The questions are:
How can I get value from array "options", I need to get the "id":
63775 and store as "item_id" and the "name":"Item" as "item_name" postman variables.
Then I need to select the "options" nested in record
"Item" and select the option "name": "Toothbrush" and store in postman
variable "svc_optn_optn_name" and it's "id" stored in
"svc_optn_optn_id"

Here I am giving my own suggestion for your problem with few lines of code. I am not sure, how are you going to use these values. I also don't know if the outer options array will always have 1 item or more. I have just tried to satisfy your questions.
Please ask/comment, if you have more doubts or I am wrong.
I have created a function getAllPostmanDataFrom(obj) which takes object as parameter which is the value of data[count], gathers necessary info in other object postmanObj and returns it to the caller.
function getAllPostmanDataFrom(obj) {
const item_id = obj.options[0].id;
const item_name = obj.options[0].name;
const svc_optn_optn_name = obj.options[0].options[1].name;
const svc_optn_optn_id = obj.options[0].options[1].id;
const postmanObj = {item_id, item_name, svc_optn_optn_id, svc_optn_optn_name}; // Return object
return postmanObj;
}
var data = [
{
"id": 20599,
"name": "Deliver",
"options": [
{
"id": 63775,
"name": "Item",
"dataType": "SelectMultiOption",
"required": false,
"options": [
{
"id": 426,
"name": "Towels"
},
{
"id": 427,
"name": "Toothbrush"
},
{
"id": 428,
"name": "Pillow"
}
]
}
]
}
]
var count = 0;
var obj = data[count];
var postmanObj = getAllPostmanDataFrom(obj);
//var {item_id, item_name, svc_optn_optn_id} = postmanObj;
console. log(postmanObj)
/*
console.log(item_id);
console.log(item_name);
console.log(svc_optn_optn_id);
console.log(svc_optn_optn_name);
*/
Finally, you can use values contained in postmanObj as follows:.
postman.setEnvironmentVariable("item_id", postmanObj.item_id);
postman.setEnvironmentVariable("item_name", postmanObj.item_name);
And so on.

This is the solution
var data = JSON.parse(responseBody);
variable named as data
var loop_count = 0
for (count = 0; count < data.length; count++)
{
if (data[count].name == "Deliver")
{
var job_id = data[count].id;
postman.setEnvironmentVariable("service_id", job_id);
var job1_name = data[count].options[0].name;
postman.setEnvironmentVariable("item_name", job1_name);
var job2_id = data[count].options[0].id;
postman.setEnvironmentVariable("item_id", job2_id);
var job3_id = data[count].options[0].options[1].id;
postman.setEnvironmentVariable("svc_optn_optn_id", job3_id);
var job4_name = data[count].options[0].options[1].name;
postman.setEnvironmentVariable("svc_optn_optn_name", job4_name);
}

const data = JSON.parse(responseBody);
data.forEach(item => {
console.log(item.id); // deliver object id.
item.options.forEach(option => {
console.log(`Option Id ${option.id}`); // option id
postman.setEnvironmentVariable("service_id", option.id);
option.options(optionItem => {
if(optionItem.name == 'Toothbrush'){
postman.setEnvironmentVariable("svc_optn_optn_name", optionItem.name);
postman.setEnvironmentVariable("svc_optn_optn_id", optionItem.id);
}
});
});
});

Related

Create JSON dynamically with dynamic keys and values in Express Js

I am fetching API into my Express server which has several JSON key value pairs in one array.
For Example:
[{
"quality": "best",
"url": "https://someurlhere.example/?someparameters"
},
{
"quality": "medium",
"url": "https://someurlhere1.example/?someparameters"
}]
And I want to create an array of JSON of that received data in this Format:
[{
"best": "https://someurlhere.example/?someparameters"
},
{
"medium": "https://someurlhere1.example/?someparameters"
}]
I have tried doing this by using for loop
for(let i=0; i < formats.length; i++){
arr.push({
`${formats[i].quality}` : `${formats[i].url}`
})
}
But it didn't work for me.
Please help me in achieving this.
Thanks in Advance :)
You could use the map function and create a new object from it.
For example:
let prevArr = [{
"quality": "best",
"url": "https://someurlhere.example/?someparameters"
}, {
"quality": "medium",
"url": "https://someurlhere1.example/?someparameters"
}]; // Replace with your array
let newArr = [];
let obj = {};
prevArr.map(function(x) {
obj = {};
obj[x["quality"]] = x.url;
newArr.push(obj);
});
const input = [{
"quality": "best",
"url": "https://someurlhere.example/?someparameters"
}, {
"quality": "medium",
"url": "https://someurlhere1.example/?someparameters"
}];
const result = input.map((v, i) => {
return {
[v["quality"]]: v["url"]
}
});
console.log(result)

How to increment values in an array json file based of from a name?

Example JSON file:
[
{
"discordId": "9273927302020",
"characters": [
{
"name": "Rare_Character",
"value": 1
},
{
"name": "Ultra_Rare_Character",
"value": 1
}
]
}
]
Let's just say for example I ran this simple gacha and got 4 characters:
let i = 1
var picks = []
while(i <= 4){
const { pick } = gacha.simple(alpha)
picks.push(pick)
i++
}
Now, picks has an array like this:
[
{
"name": "Common_Character"
},
{
"name": "Ultra_Rare_Character"
},
{
"name": "Common_Character"
},
{
"name": "Rare_Character"
}
]
How do I increment the value in My Example JSON file based on the name from what I got in my gacha results picks while ignoring the Common_Character and only passing those Rare and Ultra_Rare ones?
I've tried filtering them like this:
var filter = picks.filter(t => t.name === 'Rare_Character' || t.name === 'Ultra_Rare_Character')
Now I don't know how to increase those values in my JSON file and what if in the gacha results I got two Rare_Characters or Ultra_Rare_Character
I'm using fs to read my JSON file but I just don't know the logic to increase values
const src = [
{
"discordId": "9273927302020",
"characters": [
{
"name": "Rare_Character",
"value": 1
},
{
"name": "Ultra_Rare_Character",
"value": 1
}
]
}
];
const gacha = [
{
"name": "Common_Character"
},
{
"name": "Ultra_Rare_Character"
},
{
"name": "Common_Character"
},
{
"name": "Rare_Character"
}
];
const updateValues = (src, gacha) => {
const gachaSums = gacha.reduce((collector, current) => {
collector[current.name] = (collector[current.name] | 0) + 1;
return collector;
}, {});
src.characters.forEach(srcChar => {
gachaSums[srcChar.name] = srcChar.value + (gachaSums[srcChar.name] | 0);
});
src.characters = Object.entries(gachaSums).map(([key, value]) =>
({ name: key, value: value })
);
return src;
}
console.log(updateValues(src[0], gacha));
Maybe this version could help

How to find a key-value pair in multilevel Object?

I'm using this data structure in my Angular project. I'm not sure Angular it does matter, but maybe it has benefits:
const content = [
{
"id": 1, // language id
"name": "english",
"code": "en",
"menus": [
{
"id": 1, // group id
"lang_id": 1,
"name": "Default",
"items": [
{
"id": 2, // item id
"name": "About us",
"menu_id": 1,
"is_hidden": 0,
// ...
},
],
},
// ...
],
},
// ...
]
I know the id of the language, the group and the item too with these variable names:
private lang_id = 1;
private group_id = 1;
private item_id = 2;
In the data structure I have many "languages" with many "groups", and I have many "items" in the "groups".
I tried to use this code, but I think here need to be a better soultion:
let indexLang: number;
let indexGroup: number;
for (let i = 0; i < this.content.length; i++) {
if ( this.content[i].id === this.lang_id) {
indexLang = i;
break;
}
}
for (let i = 0; i < this.content[indexLang].menus.length; i++) {
if ( this.content[indexLang].menus[i].id === this.group_id) {
indexGroup = i;
break;
}
}
// and another for loop to find the item...
Is there a better way to find the is_hidden key-value pair with the least resources?
You are looking for Array.prototype.find.
const content = [
{
"id": 1, // language id
"name": "english",
"code": "en",
"menus": [
{
"id": 1, // group id
"lang_id": 1,
"name": "Default",
"items": [
{
"id": 2, // item id
"name": "About us",
"menu_id": 1,
"is_hidden": 0,
// ...
},
],
},
// ...
],
},
// ...
]
let lang_id = 1;
let group_id = 1;
let item_id = 2;
let language = content.find(item => item.id === lang_id);
let group = language.menus.find(item => item.id === group_id);
let item = group.items.find(item => item.id === item_id);
console.dir(item)
You for sure need to add some error handling for the case that one of the ids does not exists. And you could chain those finds:
try {
let item = content.find(item => item.id === lang_id)
.menus.find(item => item.id === group_id)
.items.find(item => item.id === item_id);
} catch( err ) {
// one of the ids did not exists
}

Creating Tableau WDC from associative array

I am creating a Tableau Web Data Connector as described in their Getting Started guide HERE.
I have implemented a similar solution previous with data from a basic associative array, but I am having trouble with my current API call.
I make an API call to an external web service that returns a JSON similar to the one listed below (simplified version)(COMMENT simply added for clarity and not part of original code).
{
"status": true,
"employee": {
"id": 123
},
"company": {
"id": 123
},
"job": {
"id": 123,
"job_workflows": [{
"id": 1,
"name": "Start",
"action_value_entered": "Start"
}, {
"id": 2,
"name": "Date",
"action_value_entered": "2017-09-11"
}, {
"id": 3,
"name": "Crew",
"action_value_entered": "Crew 3"
},
**COMMENT** - 17 other unique fields - omitted for brevity
]
}
}
For my requirements, I need to create a new column for each of my JSON job_workflows to display the data in Tableau. I.e.
Column 1 Header = Start
Column 1 value = Start
Column 2 Header = Date Complete
Column 2 value = 2017-09-11
Etc.
My Tableau JavaScript file looks as below:
(function () {
var myConnector = tableau.makeConnector();
myConnector.init = function(initCallback) {
initCallback();
tableau.submit();
};
myConnector.getSchema = function (schemaCallback) {
var cols = [
{ id : "start", alias : "Start", dataType: tableau.dataTypeEnum.string },
{ id : "date", alias : "Date", dataType: tableau.dataTypeEnum.datetime },
{ id : "crew", alias : "Crew", dataType: tableau.dataTypeEnum.string }
];
var tableInfo = {
id : "myData",
alias : "My Data",
columns : cols
};
schemaCallback([tableInfo]);
};
myConnector.getData = function (table, doneCallback) {
$.getJSON("http://some/api/call/data.php", function(response) {
var resp = response; // Response is JSON as described above
var tableData = [];
// Iterate over the JSON object
for (var i = 0, len = feat.length; i < len; i++) {
// not working
tableData.push({
"start": resp.job.job_workflows[i].action_value_entered,
"date": resp.job.job_workflows[i].action_value_entered,
"crew": resp.job.job_workflows[i].action_value_entered
});
}
table.appendRows(tableData);
doneCallback();
});
};
tableau.registerConnector(myConnector);
})();
How do I iterate over the JSON job_workflow and assign each action_value_entered to be a id in my getSchema() function? My current version simply hangs and no values are returned. NO error or warnings thrown.

one of JSON values returns unidentified with JavaScript

I need to retrieve email field from JSON with JavaScript.
Here is the code:
"contacts": [
{
"addedAt": 1332358711001,
"vid": 1,
"properties": {
"lastname": {
"value": "Mott"
},
"firstname": {
"value": "Adrian"
}
},
"identity-profiles": [
{
"vid": 1,
"identities": [
{
"type": "EMAIL",
"value": "test-fdfc6c2e-e19e-4138-8201-8342ca333aa1#hubspot.com",
"timestamp": 1332358711715
},
{
"type": "LEAD_GUID",
"value": "f3ebaf07-1c6d-4ada-af31-3559dd8b3027",
"timestamp": 1332358711771
}
]
}
]
}]
The code works with all fields, except when I get to Identities, it returns NULL or unidentified.
var temp = fields.contacts.length;
for (var i=0; i<fields.contacts.length; i++){
var addedAt = fields.contacts[i].addedAt;
var formattedDate = Utilities.formatDate(new Date(addedAt), "GMT", "yyyy-MM-dd");
var lastName = fields.contacts[i].properties.lastname.value;
var firstName = fields.contacts[i].properties.firstname.value;
var vid = fields.contacts[i].vid;
var ip = fields.contacts[i]['identity-profiles'];
var id = ip.identities;
}
var id always returns unidentified. Also doesn't work:
for (var j=0; i<id.length; j++){
if(typeof ['type'] == 'EMAIL'){
var email = id[j].value;
}
};
fields.contacts[i]['identity-profiles'] is an array, it doesn't directly have a identities property.
You may want
var id = ip[0].identities;
or you should iterate over fields.contacts[i]['identity-profiles'] but it's not clear what you precisely want.

Categories