gpt4 book ai didi

javascript - 尝试从 URL 解析 JSON 文件

转载 作者:行者123 更新时间:2023-11-28 04:40:52 25 4
gpt4 key购买 nike

这是我正在使用的 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);
});

});

`

最佳答案

由于您使用的是 $.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>

关于javascript - 尝试从 URL 解析 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43789462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com