Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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}
share
7  
why don't you use dataType as JSON and send response as JSON instead of text ?? – bipen 8 mins ago
Did you check your Javascript console for errors? – Barmar 2 mins ago

4 Answers

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
share

Need to use [] notation

data[currCounter]
share

Use

alert(data[currCounter]); 

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

share

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

share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.