Javascript - 使用for循环遍历JSON对象

时间:2015-04-15 05:59:35

标签: javascript json

我是JS的新手,我正在尝试循环使用以下JSON:

myLogger - myLogger - JSON ARRAY - {"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distance":"300","calories":"150"},{"entryID":"4","distance":"400","calories":"200"},{"entryID":"5","distance":"500","calories":"250"},{"entryID":"6","distance":"600","calories":"300"}],"success":1}

但我的控制台行继续打印:

  

myLogger - undefined - undefined - undefined

我见过成功的解决方案,例如these似乎不适合我。

我的for循环尝试如下:

    for (var key in jsonarry) {
      if (jsonarry.hasOwnProperty(key)) {
        myLogger(jsonarry[key].entryID + " - " + jsonarry[key].distance + " - " + jsonarry[key].calories);
      }
    }

    /*
    for (var key in jsonarry) {
      if (jsonarry.hasOwnProperty(key)) {
        myLogger(jsonarry[0].entryID + " - " + jsonarry[1].distance + " - " + jsonarry[2].calories);
      }
    }
    */

这是我的完整JS:

    google.load("visualization", "1", {packages:["corechart"]});

google.setOnLoadCallback(drawVisualization);

function drawVisualization() {

  var req = false;
  var jsonarry;

  try {
      // most browsers
      req = new XMLHttpRequest();

      myLogger("myLogger - XMLHttpRequest() created");
  } catch (e){
      // IE
      try{
          req = new ActiveXObject("Msxml2.XMLHTTP");

          myLogger("myLogger - req = new ActiveXObject(Msxml2.XMLHTTP);");          
      } catch (e) {
          // try an older version
          try{
              req = new ActiveXObject("Microsoft.XMLHTTP");

              myLogger("myLogger - req = new ActiveXObject(Microsoft.XMLHTTP);");               
          } catch (e){

          }
      }
  }

  if (!req) { 
    myLogger("req === false");
  } else {

    myLogger("req === true");
  }

  // Use onreadystatechange property
  req.onreadystatechange = function() {

       //myLogger("myLogger - req.onreadystatechange = function(){");

      if(req.readyState == 4) {

          myLogger("myLogger - req.readyState == 4");

          if(req.status === 200) {

            myLogger("myLogger - req.status === 200");

            jsonarry = req.responseText;

            myLogger("myLogger - JSON ARRAY - " + jsonarry);

            myLogger(" ------------- ");

            var obj = JSON.parse(jsonarry);

            myLogger("jsonarry.length == " + jsonarry.length);

            for (var key in jsonarry) {
              if (jsonarry.hasOwnProperty(key)) {
                myLogger(jsonarry[key].entryID + " - " + jsonarry[key].distance + " - " + jsonarry[key].calories);
              }
            }

            /*
            for (var key in jsonarry) {
              if (jsonarry.hasOwnProperty(key)) {
                myLogger(jsonarry[0].entryID + " - " + jsonarry[1].distance + " - " + jsonarry[2].calories);
              }
            }
            */
          } else {
            myLogger("myLogger - req.status == " + req.status);
          }

          //return req.status === 200 ? success(req.responseText) : error(req.status)
      } else {
          myLogger("myLogger - req.readyState != 4 i.e. req.readyState === " + req.readyState);
      }
  }

  req.open("GET", 'http://www.dummyurl/dbread.php', true);

  req.send(null); 
}

function myLogger(content) {
    if (window.console && window.console.log) {
        console.log("myLogger - " + content);
    }
}

2 个答案:

答案 0 :(得分:0)

您正在解析JSON字符串,而不是循环遍历已解析的值,而是循环遍历JSON strring。

var obj = JSON.parse(jsonarry);

myLogger("jsonarry.length == " + jsonarry.length);

for (var key in jsonarry) {
    if (jsonarry.hasOwnProperty(key)) {
        myLogger(jsonarry[key].entryID + " - " + jsonarry[key].distance + " - " + jsonarry[key].calories);
    }
}

使用如下。

var obj = JSON.parse(jsonarry);

myLogger("jsonarry.length == " + jsonarry.length);

for (var key in obj) {
    if (jsonarry.hasOwnProperty(key)) {
        myLogger(jsonarry[key].entryID + " - " + jsonarry[key].distance + " - " + jsonarry[key].calories);
    }
}

但是,为什么要在对象中循环?你需要在该对象内循环数组吗?

答案 1 :(得分:0)

您需要使用分配给obj的已解析JSON结果,而不是jsonarry

中的原始JSON文本

"dummmysetsJSONArr"也是一个对象数组。

试试这个:

for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
           var list=obj[key];
           list.forEach(function(item){
               myLogger(item.entryID + " - " + item.distance + " - " + item.calories);
           });
      }
 }

同时避免从jsonarry这样的变量名中删除字母,这最终会导致混淆。