我收到一个错误:
类型错误:data.forEach不是函数
我尝试了data = JSON.parse(data)
,但我得到了另一个错误:
语法错误:“[object Object]”不是有效的JSON
我想这是因为数据记录包含在一个键为content
的数组中,正如你在下面看到的。有没有一个简单的方法来获取数组content
中的数据记录?
document.addEventListener('DOMContentLoaded', initClubApi);
function initClubApi(){
renderFromApi("games/team/2").then(function(data){
renderTeams(data);
});
}
function renderFromApi(url){
return fetch(`https://www.xyz.be/api/clubapi/${url}`).then(function(response){
return response.json();
});
}
function renderTeams(data){
const target = document.querySelector("#teams-schedule");
target.innerHTML = "";
console.log(data);
data.forEach(function(row){
const teamData = `
<div class="date">${row.id}</div>
<div class="wrapper">
<div class="team-name">${row.homeTeamId}</div>
<div class="versus">VS</div>
<div class="team-name">${row.awayTeamId}</div>
</div>
`;
target.innerHTML += teamData;
});
}
下面的数据示例(仅一行)
{
"content":[
{
"viewGameReport":false,
"id":1632,
"date":"2023-08-17 19:30",
"time":"1970-01-01 01:00",
"cancelled":false,
"status":0,
"goalsHomeTeam":2,
"goalsAwayTeam":2,
"homeClub":{
"id":1690,
"name":"Sporting Keiem",
"abbreviation":"Sporting Keiem",
"logo":"https://dfaozfi7c7f3s.cloudfront.net/logos/extra_groot/1690.png?v=1",
"logoSmall":"https://dfaozfi7c7f3s.cloudfront.net/logos/klein/1690.png?v=1",
"version":1
},
"awayClub":{
"id":159,
"name":"K s v Veurne",
"abbreviation":"K s v Veurne",
"logo":"https://dfaozfi7c7f3s.cloudfront.net/logos/extra_groot/159.png?v=1",
"logoSmall":"https://dfaozfi7c7f3s.cloudfront.net/logos/klein/159.png?v=1",
"version":1
},
"competitionType":"Vriendschappelijk",
"homeTeamId":null,
"awayTeamId":2
}
]
}
完整的JSON结果:
{
"content":[],
"pageable":{},
"last":true,
"totalElements":40,
"totalPages":1,
"first":true,
"numberOfElements":40,
"number":0,
"size":2000,
"sort":{},
"empty":false
}
1条答案
按热度按时间cygmwpex1#
语法错误:“[object Object]”不是有效的JSON
当你试图解析JSON对象时,你会得到这个错误。
JSON.parse()
仅用于将JSON字符串解析为JSON对象。TypeError:data.forEach不是函数
当你试图创建一个对象时,你会得到上面的错误(根据你提到的日志输出),
Array.forEach()
用于创建一个数组而不是一个对象。试试这个**:**