My question:
I want to access a value in a certain array repetition.
This is the JSON:
{
"d": {
"results": [{
"Id": 1,
"Value": "XX"
}
],
[{
"Id": 2,
"Value": "YY"
}
]
}
}
I would like to do something like this:
var jsonData = JSON.parse(responseBody);
console.log(jsonData.d.results[Id='1'].Value);
Is it possible?
What’s the proper approach?
Thanks in advance
Here are a few examples of working with arrays…
const response = pm.response.json();
pm.test("Test", () => {
pm.expect(response).to.have.property("id", 0);
pm.expect(response.tags[0].id).to.eql(0);
pm.expect(response.tags).to.have.lengthOf(1);
});
Here is an image to show the JSON layout, to compare to the assertions above.
For a consol log you could do;
console.log(jsonData.d.results[0].id);
Note that the [0] would be looking at the first item in the array… if you wanted the second it would be [1] third would be [2] and so on (remember array indexes start at 0).
You can read more here
Sorry, I think I didn’t explain myself properly.
Maybe my example was to simple to explain what I was looking for.
I don’t want to access the value based on the index of the array (jsonData.d.results[0].value)), but on another value of the array (jsonData.d.results[Id=‘1’].Value).
In XPATH this is achievable without iterating all the entries, using expressions like:
Get all the book which genre is Romance:
//book[genres/genre = 'Romance']
Thanks anyway.
Maybe try something like;
const response = pm.response.json();
_.each(pm.response.json().book, (book) => {
if(book.genre === "Romance"){
console.log(book.genre)
}
})
1 Like
You could also use .find() to get the object which has an Id
of 1
let obj = pm.response.json().d.results.find(e => e.Id === 1);
console.log(obj.Value);
3 Likes