Dealing with JSON result

牧云@^-^@ 提交于 2020-01-05 12:08:10

问题


I'm having trouble reading the JSON data from a venues search. Here is my code:

xmlhttpRC = new XMLHttpRequest();
url = "https://api.foursquare.com/v2/venues/explore?ll="+pointStrr+"&oauth_token=V5PI2GJ0KDOVH2GAHNHJ5DVLMRKNF440FR1N1HPG0XHX2OBQ&v=2015643&
callback=JSONP";
xmlhttpRC.open("GET", url, true);
xmlhttpRC.onreadystatechange = recCb;      
xmlhttpRC.send(null);
//return recommendedArr;
}

function recCb(data){
//console.log(data);
if(xmlhttpRC.readyState == 4){
    if(xmlhttpRC.status == 200){
        var recRes = xmlhttpRC.response;

        console.log(recRes);

        //console.log(recRes);
        console.log(recRes.meta.code);
    }
}

}

I get the reponse I expect from the server, and firebug shows me that a JSON object is returned, but I am not sure how to access the data inside from here.

console.log(recRes.meta.code) returns the error:

"recRes.meta is undefined"

Where am I going wrong? I want to access the venues information but I am just using meta.code as a simple test. This is probably really simple but I'm stumped!

Thanks in advance, Ross.


回答1:


var decodedResp = JSON.parse(recRes);
if (decodedResp.meta.code === ...) 

JSON-object is just a representation of an JS-object, see; it should be parsed first.




回答2:


You need to parse JSON. Modern browsers have JSON.parse built in, older versions of IE etc. do not - you can theoretically use eval(response) but it creates a security hole.

There is a library to parse it if you cannot depend on users having modern browsers.



来源:https://stackoverflow.com/questions/9422372/dealing-with-json-result

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