简体   繁体   English

无法从嵌套的Json数据检索数据

[英]Fail to retrieve data from nested Json data

in the following code, i was trying to extract data from json, and there was few errors occur, which i dont understand. 在以下代码中,我试图从json提取数据,并且几乎没有发生错误,我不理解。 In my previous post, someone mentioned that it was related to closure issues. 在我以前的帖子中,有人提到它与关闭问题有关。 Can anyone please explain why this issues still occur eventhough i already change the "var" to "let" in both for loop? 任何人都可以解释为什么即使我在两个for循环中都已经将“ var”更改为“ let”,为什么仍然会出现此问题?

I would like to try the bind solution, but, i dont understand the steps. 我想尝试绑定解决方案,但是,我不理解这些步骤。 this is because i am referring to for loop array in json file. 这是因为我指的是json文件中的for循环数组。

function displayData(data) {
var json = JSON.parse(data);

alert (json.projects[0].task_data[1].taskName); //working

for (let i = 0; i < json.projects.length; i++) {

    $.ajax({ url: epridlist, method: 'GET' }).then(function (datas) {
          alert (json.projects[i].projName); //success load the value
    });

    for (let j = 0; j < json.projects[i].task_data.length; j++) { 
        $.ajax({url: tasklist,method: 'GET'}).then(function (data) 
        {alert (json.projects[i].task_data[j].taskName);});//success only on first row, next row value is undefined  
         alert (json.projects[0].task_data[1].taskName); //undefined          
    }
}
}

this is the json data 这是json数据

{"projects":[{"projName":"1","task_data":[{"taskName":"1","task_detail_data":[{"h_sun":"0.00","h_mon":"0.00","h_tue":"0.00","h_wed":"0.00","h_thu":"0.00","h_fri":"0.00","h_sat":"0.00"}]},[{"taskName":"2","task_detail_data":[{"h_sun":"0.00","h_mon":"0.00","h_tue":"0.00","h_wed":"0.00","h_thu":"0.00","h_fri":"0.00","h_sat":"0.00"}]}]]},{"projName":"2","task_data":[{"taskName":"3","task_detail_data":[{"h_sun":"0.00","h_mon":"0.00","h_tue":"0.00","h_wed":"0.00","h_thu":"0.00","h_fri":"0.00","h_sat":"0.00"}]}]}]}

Thanks 谢谢

It seems your JSON data has inconsitant structure. 看来您的JSON数据结构不一致。

When viewing JSON in Json Viewer program first element of task_data is an object while the second is an array (see below picture): Json Viewer程序中查看JSON时, task_data第一个元素是一个对象,而第二个是数组(请参见下图):

在此处输入图片说明

Below line in your code will cause an issue: 您的代码下面的行会引起问题:

json.projects[0].task_data[1].taskName

This problem occur here: json.projects[0].task_data[1].taskName you're triying to accede an object how does not exists. 此问题发生在这里: json.projects[0].task_data[1].taskName您正在尝试加入一个对象,该对象不存在。 task_data array in the second position is an array, not an object. 第二个位置的task_data数组是数组,而不是对象。 The soluction to your problem is use json.projects[i].task_data[0].taskName acceding to the object instead of the array. 解决该问题的方法是使用json.projects[i].task_data[0].taskName代替对象,而不是数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM