2

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}
2
  • 8
    why don't you use dataType as JSON and send response as JSON instead of text ?? Commented Jun 4, 2013 at 6:58
  • Did you check your Javascript console for errors? Commented Jun 4, 2013 at 7:03

4 Answers 4

14

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @DhruvPathak .. It just worked by using [] instead of "."
2

Need to use [] notation

data[currCounter]

Comments

2

Use

alert(data[currCounter]); 

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.