这是我正在使用的json:json
我希望能够从中提取不同的数据并将其显示在网页上。特别是徽章名称和相关信息。徽章阵列给我带来了麻烦。
我在这里查看了jquery文档:http://api.jquery.com/jquery.getjson/ 但他们失去了我,因为它与我想做的事情不相符。
这是我试过的js文件没有运气...谢谢
`
//Function to print message to console
function printMessage(badgeCount, points, arr) {
const message = `Anthony Scott has ${badgeCount} total badge(s) and ${points} points in JavaScript. here is a list of badges ${arr}`;
document.write(message);
}
(function() {
$.getJSON("https://teamtreehouse.com/anthonyscott4.json", {})
.done(function(data) {
// Parse the data
const profile = JSON.parse(data);
// Print the data
let arr = [];
for(var x in profile.badges) {
arr.push(profile.badges[x].name)
}
document.write(profile.badges.length, profile.points.JavaScript, arr);
});
});
`
答案 0 :(得分:0)
由于您使用的是$.getJSON
,因此在回调中已经为您解析了JSON
,因此无需在结果上调用JSON.parse
。
for in
循环用于iterate over an objects properties。您正在寻找的是正常的for
循环或forEach
var request = $.getJSON('https://teamtreehouse.com/anthonyscott4.json');
request.done(function (response) {
var badges = [];
response.badges.forEach(function (badge) {
badges.push(badge.name);
});
$('#result').append(badges.toString());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
for
循环示例:
var request = $.getJSON('https://teamtreehouse.com/anthonyscott4.json');
request.done(function (response) {
var badges = [];
for (var i = 0; i < response.badges.length; ++i) {
var badge = response.badges[i];
badges.push(badge.name);
}
$('#result').append(badges.toString());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>