I'm trying to access some data which is in a json file. I read the data through AJAX and try to traverse through the data.
Here's my json file.
{"data":[{"LotNo":"1", "UnitNo":"1"}, {"LotNo":"2", "UnitNo":"2"}]}
And the function in my html file.
function X1(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
X2(myObj);
}
};
xmlhttp.open("GET", "test.txt", true);
xmlhttp.send();
}
And the function in the same file which uses the object.
function X2(obj)
{
var dataObject = JSON.stringify(obj);
alert(dataObject.length); //Gives me 64
}
Why does it give me 64?
Why can't I access the data array like this?
alert(dataObject.data.length);
Or
alert(dataObject.data[0]);
It gives me the error that 'data' is undefined.
How can I get to the elements of this array?
objinto a string, and when callinglengthit returns 64, the length of the string. As said by @georg, remove method JSON.stringify.