0

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?

11
  • data['result'] is undefined, but that assumes there is a result property in data. Have you checked the value of xhr.responseText and of data itself to see if the structure is maybe just slightly different than you expected? Commented Jul 27, 2017 at 10:20
  • there's something wrong with your JSON. check the JSON with an online json-checker: jsonlint.com Commented Jul 27, 2017 at 10:20
  • try console.log(data) after JSON.parse line and see the output Commented Jul 27, 2017 at 10:21
  • I think the error is in for var statement where length is called as it is where length is used. Can you please check that the error is not there. You may want to console data['result] there. Commented Jul 27, 2017 at 10:22
  • 3
    "xhr.'responseText' and 'data' (which is the same) " - Which is not the same, because the first is the encoded, and the second one is the decoded version. They may both be string, but I can't imagine that they are actually exactly the same string. Please check carefully, because I imagine that that is the cause of the problem: The result of decoding your JSON, is just another string. Commented Jul 27, 2017 at 10:44

1 Answer 1

1

You expect xhr.responseText to contain a JSON encoded object. It looks like it actually contains a JSON encoded string (and that the JSON encoded string contains a JSON encoded object). Note the " characters around xhr.responseText when you console.log it.

That is to say: You have an object which has been encoded as JSON which has then been encoded as JSON again.

When you run JSON.parse(xhr.responseText), you decode the first layer of JSON encoding. This gives you a string of JSON that represents an object.

That string doesn't have a result property.

You need to decode the second set to JSON to get your object:

var json = JSON.parse(xhr.responseText);
var data = JSON.parse(json);
console.log(data.result.length);

console.log("Compare single encoded data:");
var json_obj = "{ \"result\": [] }";
console.log("JSON Object: " + json_obj);
var obj = JSON.parse(json_obj);
console.log("Object result length", obj.result.length);
console.log("-------------");
console.log("With double encoded data:");
var json_str = "\"{ \\\"result\\\": [] }\"";
console.log("JSON String (See the extra quotes?): " + json_str);
var json_obj_2 = JSON.parse(json_str);
console.log("JSON Object 2: " + json_obj_2);
var obj_2 = JSON.parse(json_obj_2);
console.log("Object 2 result length", obj.result.length);


A better solution would be to figure out why the data was being double encoded in the first place and not do that.

Sign up to request clarification or add additional context in comments.

3 Comments

I cant see that the string is double time strigified.
@YashGanatra — Look closer then? I can. You can see the quotes around it when it is logged (as I said).
@Quentin Your solution is delicious! I actually had double-encoded json. Just server-side problem. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.