Extract value from array of objects in Postman - json

I want to extract Id value from the array with objects in Postman and then set it as an environment variable. In case JSON response is an object, the following script works, but not with an array of objects (my array has only one object).
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("userid", data.Id);
JSON response:
[
{
"Id": 1287,
"LastName": "Trump",
"FirstName": "Donald",
"MiddleName": "Von",
"City": "New York City",
"Phone": "66 77 88",
"State": "New York",
"Fax": "111-222-333",
"ReferenceId": "12345",
"Active": false,
"CurrentWorkingSchemeId": null
}
]

If it is an array of objects, then just select the first object using index [0] before grabbing the object's key like this:
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("userid", data[0].Id);

This works like charm!
Basically what i am doing here is, parse the response and from the data array, take id and save it in postman environment variable.
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.data.length; i++) `
{
var counter = jsonData.data[i];
postman.setEnvironmentVariable("schID", counter.id);
}

Related

How to avoid extra nesting in json string

I tried to create json string according to syntax from wikipedia. I created json string with the following code:
var data = [];
data.push(
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 27,
});
var addressdata = [];
addressdata.push(
{
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
});
data.push(
{
"address" : addressdata
}
);
The string is correct json string. However, the json structure contains some unnecessary nesting, as shown in the Figures 1 and 2 below. More precisely, there are surplus braces for address block, and the string is also enclosured with brackets instead of braces. So, what am I doing wrong? How can I avoid this unnecessary nesting and get structure as shown in Fig. 3?
Fig. 1
Fig. 2
Fig. 3
The string is generated with jsonData : data, in Ajax request.
You are using a list for the data variable. That's why you get brackets in the beginning and end of the JSON body. To overcome this problem you can declare the whole JSON body in the data variable like:
data = {
"firstname": "test",
(...)
"address": [{
"streetAddress": "test"
(...)
}]
}

Parsing JSON data from Postman

I am trying to parse a JSON response from Postman that is not cooperating. Here is the body response:
{
"teams": [
{
"id": "MI6",
"name": "James Bond's Workspace",
"color": "#04a9f4",
"avatar": null,
"members": [
{
"user": {
"id": 007,
"username": "James Bond",
"email": "blahblah#gmail.com",
"color": "#e65100",
"profilePicture": null,
"initials": "JB",
"role": 1,
"custom_role": null,
"last_active": "1609978205632",
"date_joined": "1609897014429",
"date_invited": "1609897014429"
}
}
]
}
]
}
I am using the following test scripts that can't seem to resolve the [ value after teams.
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("teams_id", jsonData.teams.id);
postman.setEnvironmentVariable("teams_id", jsonData.teams.user.id);
It is creating the variable for me, but will not store the value of MI6 or the value of 007.
You're trying to access values that are in an object, inside an array.
Specifying the object you need with [0] because it's the first object in the array, will get the value. You would also need to do the same with members.
This should be what you need:
var jsonData = pm.response.json();
pm.environment.set("teams_id", jsonData.teams[0].id);
pm.environment.set("user_id", jsonData.teams[0].members[0].user.id);
Danny thanks for your response. I found another thread about parsing json data from an array and used this response to fix the issue. Here is what worked:
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.teams.length; i++) {
var teams_id = jsonData.teams[i];
console.log(teams_id.id);
console.log(teams_id.name);
postman.setEnvironmentVariable ("teams_id",teams_id.id)
postman.setEnvironmentVariable ("teams_name",teams_id.name)
}

getting the error like JSON schema is not correct. Enter specified JSON scehma.,Create an Array of Favorite fruits Object

0
I have the following assessment which is to Create Array of Favorite Food items object in data.json file.
The Array of Objects should have the following fields :
Name
Type
Price
After writing the JSON data, this file should be imported in loopobject.js.
I tried the above request with the below data.json
data.json
"{[{\"Name\":\"Apple\",\"Type\":\"fruit\",\"Price\":123},{\"Name\":\"pizza\",\"Type\":\"italian\",\"Price\":360},{\"Name\":\"burger\",\"Type\":\"mac&cheese\",\"Price\":321},{\"Name\":\"jangri\",\"Type\":\"sweet\",\"Price\":329}]}"
loopObject.js
var json = require('./data.json');
json.forEach(function(object) { console.log(object.Name); });
verify.js
const Joi = require('joi');
const fss =require('fs');
const schema = Joi.array().min(3).has({
Name: Joi.string().required(),
Type: Joi.string().required(),
Price: Joi.number().required(),
});
var data;
try{
data = require("./data.json");
}catch(e)
{
data={};
}
var XMLWriter = require('xml-writer');
xw = new XMLWriter;
const result = Joi.validate(data, schema);
// You can also pass a callback which will be called synchronously with the validation result.
Joi.validate(data, schema, function (err, value) {
if(err==null)
{ console.log("JSON is valid.");
}else{
console.log("JSON schema is not correct. Enter specified JSON scehma.");
}
});
i have tried couple of ways, everything looks good,but don't know where i am doing mistake. Could you please help on this??
The JSON format is not correct, try this one:
data.json
[
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
}
]
The JSON data describes an array, and each element of that array is an object.

How can I loop through values in my json file?

suppose I have a json file and I would like to loop through the values like so:
var myModel = {"id": 0, "date": "2014-10-28", "amount": 1111, "productId": "2", "description": "Cash"};
for (value in myModel)
{
//element(by.model(key)).clear().sendKeys(value);
}
This is a part of a jasmine script but it is not the point. The question is how can I loop through my model per key i.e 'id','date' etc and their values in angular js?
i think you need this:
for (key in myModel) {
console.log("key is :",key)
console.log("value is:",myModel[key])
}
Angular foreach will do the trick
Invokes the iterator function once for each item in obj collection,
which can be either an object or an array. The iterator function is
invoked with iterator(value, key, obj), where value is the value of an
object property or an array element, key is the object property key or
array element index and obj is the obj itself. Specifying a context
for the function is optional.
var values = {"id": 0, "date": "2014-10-28", "amount": 1111, "productId": "2",
"description": "Cash"};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
console.log(log);
Fiddle

How to parse json data using prototype.js and iterate through it?

I have json array like
var data = '[{ "name": "Violet", "occupation": "character" },{ "name": "orange", "occupation": "color" }]'
How to parse the the data and iterate through it using prototype.js?
There is a function called evalJSON()
var data = '[{ "name": "Violet", "occupation": "character" },{ "name": "orange", "occupation": "color" }]';
data = data.evalJSON();
//for more security:
data = data.evalJSON(true); //sanitizes data before processing it
Then just use for to iterate through the array:
for (var i=0;i<data.length;i++)
{
//do whatever you like with data[i];
}
Or use the prototypeJS .each() function:
data.each(function(el){
//do whatever you like with el
});