我正在使用dexi.io机器人自动从许可证数据库中提取数据。该机器人将接受自定义JavaScript来解析传入的JSON对象。
此代码在某些情况下似乎可以工作-正确解析传入的JSON-但几乎在每种情况下都失败。错误是无法读取长度未定义的属性。
以下是适用的测试api:https://services.odata.org/V4/TripPinService/People
这是代码:
var people = JSON.parse(json).value;
var arr = [];
function getCountry(member) {
try {
return member.fields.name;
} catch(err) {
return "";
}
}
for (i = 0; i < people.length; i++) {
var member = people[i];
var obj =
{
"name": member.name,
"Country": getCountry(member),
"alias": member.alias
};
arr.push(obj);
}
return arr;
答案 0 :(得分:0)
检查您的第一行“ json”。我认为您没有定义要从中获取数据的json文件。
答案 1 :(得分:0)
不确定要获取响应的确切方式,但是我能够轻松完成此工作:
fetch("https://services.odata.org/V4/TripPinService/People")
.then(response => response.json())
.then(data => {
var people = data.value;
var arr = [];
function getCountry(member) {
try {
return member.AddressInfo[0].City.CountryRegion;
} catch(err) {
return "Country Info Not Available";
}
}
for (i = 0; i < people.length; i++) {
var member = people[i];
var obj =
{
"name": member.FirstName,
"Country": getCountry(member),
"alias": member.alias
};
arr.push(obj);
}
console.log(arr);
});
也许这会给你一些想法。
答案 2 :(得分:0)
我已经检查了给定URL中的json。因此,在您的代码中,“ member.name”,“ member.alias”,“ member.fields.name”之类的属性不存在。 尝试使用json中的确切属性名称:
{
"@odata.context": "http://services.odata.org/V4/TripPinService/$metadata#People",
"@odata.nextLink": "https://services.odata.org/V4/TripPinService/People?%24skiptoken=8",
"value": [
{
"@odata.id": "http://services.odata.org/V4/TripPinService/People('russellwhyte')",
"@odata.etag": "W/\"08D817F8EC7DAC16\"",
"@odata.editLink": "http://services.odata.org/V4/TripPinService/People('russellwhyte')",
"UserName": "russellwhyte",
"FirstName": "Russell",
"LastName": "Whyte",
"Emails": [
"Russell@example.com",
"Russell@contoso.com"
],
"AddressInfo": [
{
"Address": "187 Suffolk Ln.",
"City": {
"CountryRegion": "United States",
"Name": "Boise",
"Region": "ID"
}
}
],
"Gender": "Male",
"Concurrency": 637285705159912400
}
]
}
我想说的是准确地在json中使用名称,例如“ member.UserName”,“ member.AddressInfo [0] .Name”等。