目前使用的是Postman最新版本:6.7.4(Latest)
Currently using the latest version of Postman: 6.7.4 (Latest)
我正在尝试从 JSON 响应正文中获取一个值并将其存储在环境变量中,但值用户名"应该等于我的首选用户名.
I'm trying to get a value out of a JSON response body and store it in an environment variable BUT the value 'username' should be equal to my preferred username.
通常我会提取这样的值:
Normally I would extract a value like this:
var jsonData = pm.response.json();
pm.environment.set("useridToken", jsonData.Customers[0].userid);
这会给我列表中的第一项,但我确实不希望获得列表中的第一项或第二项.例如,我希望获得 userid
where username
EQUAL Billy".
This would give me the first item in the list but I do not wish to obtain the first nor the second item from the list. I wish to obtain the userid
where username
EQUAL "Billy" for example.
身体响应的输出:
{
"Customers": [
{
"id": 24,
"userid": 73063,
"username": "BOB",
"firstname": "BOB",
"lastname": "LASTNAME
},
{
"id": 25,
"userid": 73139,
"username": "Billy",
"firstname": "Billy",
"lastname": "lasty"
}
]
}
有什么建议吗?
我记得在 SoapUI 中是这样的:
I remember in SoapUI it was like this:
$.channels[?(@.is_archived=='false')].id[0]
我想在 Postman 的 JS 中不可能做到这一点?
I guess it's not possible to do this in JS in Postman?
你可以使用:Array.prototype.find():
const data = {
"Customers": [{
"id": 24,
"userid": 73063,
"username": "BOB",
"firstname": "BOB",
"lastname": "LASTNAME"
},
{
"id": 25,
"userid": 73139,
"username": "Billy",
"firstname": "Billy",
"lastname": "lasty"
}
]
}
const user = data.Customers.find(u => u.username === 'Billy')
const userid = user ? user.userid : 'not found'
console.log(user)
console.log(userid)
这篇关于邮递员从 JSON 中获取值,其中等于使用 javascript 的数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!