需要从API响应中将Id的值设置为环境变量我尝试了此操作但出现错误
'TypeError | Cannot read property 'DisplayName' of undefined'
我编写了代码,我能够获得DisplayName=Samsung XCover 4
的ID,但是无法将ID设置为环境变量。
eval(globals.bigint_fix);
var jsonData = JSON.parse(responseBody);
for (var i=0; i<=jsonData.Offerings.length; i++)
{
if(jsonData.Offerings[i].DisplayName === "Samsung XCover 4")
{
pm.environment.set("offering", jsonData.Offerings[i].DisplayName.Id);
}
}
错误:
TypeError |无法读取未定义的属性“ DisplayName”
API响应:
{
"Offerings": [{
"Amount": 28592,
"CurrencyCode": "USD",
"DisplayName": "Samsung XCover 4",
"Id": 1910256761716000500,
"Language": "en-CA",
"LineOfBusinesses": [
10048
],
"MarketingViews": [],
"Name": "Samsung XCover 4",
"OfferType": 1,
"ShortDescription": "Offering bundle includes:\n- Airtime"
}]
}
答案 0 :(得分:2)
有两个问题。首先将i<=jsonData.Offerings.length
更改为i<jsonData.Offerings.length
。其次,这行jsonData.Offerings[i].DisplayName.Id
将引发另一个错误,因为DisplayName
的值是一个字符串,并且其中没有名称为id
的键。
用jsonData.Offerings[i].Id
let jsonData = {
"Offerings": [{
"Amount": 28592,
"CurrencyCode": "USD",
"DisplayName": "Samsung XCover 4",
"Id": 1910256761716000500,
"Language": "en-CA",
"LineOfBusinesses": [
10048
],
"MarketingViews": [],
"Name": "Samsung XCover 4",
"OfferType": 1,
"ShortDescription": "Offering bundle includes:\n- Airtime"
}]
}
for (var i = 0; i < jsonData.Offerings.length; i++) {
if (jsonData.Offerings[i].DisplayName === "Samsung XCover 4") {
console.log(jsonData.Offerings[i].Id);
}
}