我正在尝试使用请求nodejs模块访问JSON GET响应中的属性。
当我收到回复时,我似乎无法打印特定属性。每次我尝试打印属性时,我都会收到一个错误,说明它未定义。
我尝试了字符串化和解析JSON,但两者都不起作用。提前谢谢。
var request = require("request");
//The search query
var query = "TGI fridays";
//path of http request
var path = "https://maps.googleapis.com/maps/api/place/textsearch/json?query="+query+"&sensor=false&key=AIzaSyA-adbJAXBmOTGINrhWHskm4d7UU9dgnOU";
//function to print the json
var parser = function(text){
console.log(text);
}
//http request with callback
request(path,function(error, response, body){
parser(body.next_page_token); //a property from the json that comes up as undefined
})
继承了一些json
{
"debug_info" : [],
"html_attributions" : [],
"next_page_token" : "CjQsAAAAM5EDuFB7u9bIQ_3KeBsa894EjYv4ca3GVN45O2cBPWUaDFkebH7r_WQy2Jf-QqZZEhDUipJwL4YXDtanJ0euTGe4GhTs6PW_jM0Ops33vWwD-5aGsk7giQ",
"results" : [
{
"formatted_address" : "403 Camino Del Rio South, San Diego, CA, United States",
"geometry" : {
"location" : {
"lat" : 32.760091,
"lng" : -117.161897
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/bar-71.png",
"id" : "29f39df87b93cf8b98062fdccc877a61fb45925a",
"name" : "TGI Fridays",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 782,
"html_attributions" : [],
"photo_reference" : "CoQBdgAAAFw5rZL8KjKfsBudSV-fNyRQUy5kflYnWJUrsN8PHzVsrP8v3R5eCKkRJOUj8fXnAtXnZZ34G5BRoNys7mLd0QJ3LEj-tLeY9LSs4B9jOyNpaNAszEZDh9kyQkfWr4POMxqwKCYN5gxFsMB4-NvGoG3sFZaOOySOKs6vVNPPL9fVEhCKe8eESOot42-Zxm4MBPPaGhSsiMuJbzuIzOpqTcEHEsL1c6GXYg",
"width" : 1146
}
],
"price_level" : 2,
"rating" : 3.2,
"reference" : "CnRpAAAAp9SAKVfthj4gk3rSghMmI3_ZJaGTzGPhVtDsdtSyG3WunYPrYEN7dAA0iEmmsTLx3ANN9FAZZ6bVNnyUxWAwEFe8a-IsTSJZwNTYq-6fMujMZJgjTWgSSWo5LXy88NdccA3l-PQ2pX2Dnz4SnLy0dhIQ_hVBBDjk8QV2oOS-THq3BBoUKOSwQjmKFn5KeJq43p4JIkANwPU",
"types" : [ "bar", "restaurant", "food", "establishment" ]
},
答案 0 :(得分:1)
Body是一个字符串。尝试:
//http request with callback
request(path,function(error, response, body){
body = JSON.parse(body);
parser(body.next_page_token); //a property from the json that comes up as undefined
})
结果(非常大的字符串):
CjQsAAAAls3nW7k5vyODIeouCv_HT_PBhB9s7KNftqBRiDWtJR3RY_KOLthW4TFj-2HNlnezEhDiq73Z83kFvtpQqWfuBb-AGhT6yoVHZHNe1EmM3UWe34jfs65oHg
注意:您也可以使用此表单告诉request
您期望json:
request.get({url: path, json:true},function(error, response, body){
parser(body.next_page_token); //a property from the json that comes up as undefined
})