Can't access property in returned object

馋奶兔 提交于 2019-12-25 07:48:03

问题


I've got a problem where I can't seem to query my JSON coming back, I can print out the entire response though, here's my JSON response, I can only see this when I do a msgBox() prompt:

{ "Addresses" : 
    "[{ 
        Building=Megatron Skyscraper,
        BuldingId=1998,
        AccountId=2000,
        Number=007,
        Name=Megatron 
        },{
        Building=StarScream Skyscraper,
        BuldingId=1999,
        AccountId=2001,
        Number=008,
        Name=StarScream
}]"}

And here's my code:

function getReadyStateHandler(req)
{
    // Return an anonymous function that listens to the
    // XMLHttpRequest instance
    return function ()
    {
        // If the request's status is "complete"
        if (req.readyState == 4)
        {
            // Check that a successful server response was received
            if (req.status == 200)
            {
                msgBox("JSON Response recieved...");
                var addresses = req.responseText.toJSON();
                msgBox(req.responseText.toJSON());
            }
            else
            {
                // An HTTP problem has occurred
                alert("HTTP error: " + req.status);
            }
        }
    }
}

I've tried everything from addresses.Address[0].City and addressess.Addresses[0].City and many others - but this is slightly confusing!


回答1:


Apart from the fact that there's no City key in your response, your returned object contains only one (malformed) string, not an array of objects. You can check this using http://jsonlint.com

How did you create the response? It should look more like:

{ "Addresses" : [{ 
        "Building":"Megatron Skyscraper",
        "BuldingId":1998,
        "AccountId":2000,
        "Number":7,
        "Name":"Megatron"
        },{
        "Building":"StarScream Skyscraper",
        "BuldingId":1999,
        "AccountId":2001,
        "Number":8,
        "Name":"StarScream"
}]}

Update: those leading zeros in "Number":007 and "Number":008 may cause problems, because they will be interpreted as octal values. I've removed them in my answer.




回答2:


Your response is valid but Addresses is a string and not an array. The quotes shouldn't be there if it is to be treated like an array. You could hack it a bit if you wanted and do

address = JSON.parse(addresses.Addresses);



来源:https://stackoverflow.com/questions/6153295/cant-access-property-in-returned-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!