Why I can't to convert a string (JSON format) to an object?
This is js function that receives a JSON formatted string from server:
function GetData(){
xhr = new XMLHttpRequest;
xhr.open('GET', 'http://'+ ip + ":" + port + "/api/s", true);
xhr.onreadystatechange = function () {
if (xhr.status == 200 && xhr.readyState == 4) {
try {
var data = JSON.parse(xhr.responseText);
for (var i=0; i<data['result'].length; i++) {
...some operations here...
}
}
catch(e) {
console.log(e.message + " in " + xhr.responseText);
return}
}
}
xhr.send();
}
But I get string, JSON.parse not work:
Cannot read property 'length' of undefined in "{\"result\":[{\"id\":1, \"region\":\"\u0420\u0435\u0441\u043f\u0443\u0431\u043b\u0438\u043a\u0430 \u0410\u0434\u044b\u0433\u0435\u044f\"}, {\"id\":2, \"region\":\"\u0420\u0435\u0441\u043f\u0443\u0431\u043b\u0438\u043a\u0430 \u0411\u0430\u0448\u043a\u043e\u0440\u0442\u043e\u0441\u0442\u0430\u043d\"}, {\"id\":3, \"region\" ... and so on ...
I can't get length of JSON-object property value, can't to access to it's property 'result' and so on.
But why?
data['result']is undefined, but that assumes there is a result property indata. Have you checked the value ofxhr.responseTextand ofdataitself to see if the structure is maybe just slightly different than you expected?