3

I am trying to parse a JSON in Javascript. The JSON is created as an ajax response:

$.ajax(url, {
  dataType: "text",
  success: function(rawData, status, xhr) {
    var data;
    try {
      data = $.parseJSON(rawData);
      var counter = data.counter;
      for(var i=1; i<=counter; i++){
        //since the number of 'testPath' elements in the JSON depend on the 'counter' variable, I am parsing it in this way
        //counter has the correct integer value and loops runs fine
        var currCounter = 'testPath'+i ;
        alert(data.currCounter); // everything alerts as undefined
      }
    } catch(err) {
      alert(err);
    }
  },
  error: function(xhr, status, err) {
    alert(err);
  }
});

But all values alert 'undefined' as value (except the 'counter' which gives correct value) The actual string as seen in firebug is as below:

{"testPath1":"ab/csd/sasa", "testPath2":"asa/fdfd/ghfgfg", "testPath3":"ssdsd/sdsd/sds", "counter":3}
basZero
  • 4,129
  • 9
  • 51
  • 89
Riju Mahna
  • 6,718
  • 12
  • 52
  • 91

4 Answers4

15

alert(data[currCounter]) , this will work.

as data.currCounter looks for the key 'currCounter` in the object, not by the value of currCounter.

example:

http://jsfiddle.net/bJeWm/1/

var myObj = { 'name':'dhruv','age':28 };
var theKey = 'age';
alert(myObj.theKey);  // undefined
alert(myObj[theKey]); // 28
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
3

Use

alert(data[currCounter]); 

instead. You cannot access a property like you did....

bipen
  • 36,319
  • 9
  • 49
  • 62
sjkm
  • 3,887
  • 2
  • 25
  • 43
2

Need to use [] notation

data[currCounter]
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
1

Try data[currCounter] because there is no value in data.currCount.