gpt4 book ai didi

javascript - 使用 jQuery 进行 JSON 树搜索,错误

转载 作者:行者123 更新时间:2023-12-02 17:46:43 26 4
gpt4 key购买 nike

我一直在使用 stackoverflow 上其他问题的代码,例如 herehere

当我尝试运行我的函数时,我收到错误Uncaught TypeError: Cannot read property 'length' of undefined,我可以在开发人员控制台中看到该错误。这个错误应该是在 jQuery 文件本身中,而不是在我的代码中。 (我知道 ofc 这仍然是我自己的错误)。

这是我尝试执行的代码:

function populate_api(){
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "test.txt",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})(); //^-from SOflow: https://stackoverflow.com/questions/2177548/load-json-into-variable
//Put the JSON into a variable ---^


$.each(json.result.matches.players, function(i, v){
if (v.account_id == 38440257) {
alert(v.hero_id);
return;
}
}); //use variable to run a search on the JSON tree --^
}

带有 Json 的文件本身包含相当多的信息,但这是我一直在测试的文件顶部的小区域:

{
"result": {
"status": 1,
"num_results": 10,
"total_results": 500,
"results_remaining": 490,
"matches": [
{
"match_id": 514348401,
"match_seq_num": 468628758,
"start_time": 1392061295,
"lobby_type": 7,
"players": [
{
"account_id": 38440257,
"player_slot": 0,
"hero_id": 42
},
...

再次快速总结一下。我正在匹配树中搜索帐户 ID 为 38440257 的“hero_id”。

最佳答案

这是因为 json.result.matches.playersundefined 并且 jQuery.each() 没有对第一个进行任何检查参数是未定义,它假设您向它传递了一些有效的东西,它可以访问其length属性。

在 JSON 中,json.result.matches 是一个对象数组(每个对象代表一场比赛),每个对象都有一个 players 属性;数组本身没有players属性。您需要首先遍历每场比赛,然后遍历每个玩家:

$.each(json.result.matches, function(index, match) {
$.each(match.players, function(i, v) {
// code here
});
});

或者只检查特定比赛的球员(在本例中为第一场比赛):

$.each(json.result.matches[0].players, function(i, v) {
// code here
});

您还应该放弃同步 AJAX 调用(这样一个荒谬的概念......),而是从成功回调函数中使用数据处理逻辑调用函数,并传入 JSON。

关于javascript - 使用 jQuery 进行 JSON 树搜索,错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21699167/

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