pablovok
(Pablo)
1
Hello,
I want to validate a piece of the json’s response, but the data varies its position … I thought something like that … but it does not work for me.
Example:
pm.test(‘Validate date’, function() {
var idDate;
if((jsonData.date[0].id).exist){
pm.expect(jsonData.date[0]).to.have.property(‘id’);
idDate = jsonData.date[0].id;
} else {
pm.expect(jsonData.date).to.have.property(‘id’);
idDate = jsonData.date.id;
}
console.log(idDate);
pm.environment.set(“IdDATE-TEMP”, idDate);
});
Thanks and regards.
Pablo.
1 Like
pablovok
(Pablo)
2
I solved it with a try catch 
Try to look for it in one position and if it does not find it, look for it in the other.
Hi @pablovok, just wanted to weigh in here about using lodash which is inbuilt in Postman and how you can easily get around this code piece.
Using the _.get
method from lodash, which allows safe extraction you’ll be able to avoid try...catch
blocks.
pm.test('Validate date', function () {
var idDate = _.get(jsonData, 'date[0].id');
if (idDate) {
pm.expect(jsonData.date[0]).to.have.property('id');
} else {
pm.expect(jsonData.date).to.have.property('id');
idDate = _.get(jsonData, 'date.id');
}
console.log(idDate);
pm.environment.set('IdDATE - TEMP', idDate);
});
8 Likes