gpt4 book ai didi

node.js - 读取 Google 响应 JSON 文件

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:55 25 4
gpt4 key购买 nike

首先,我对此很陌生,如果这对你们中的一些人来说是“常识”,我很抱歉。

因此,使用 Node.js 的请求包,我想向 Google Places API 发送 HTTP 请求,而 API 则使用 JSON 文件进行响应,而我很难使用该文件。

我的请求代码:

request(url_nearby, {json: true}, function(err, resp, body){
if(err){
console.log(err);
}else{
console.log(body);
}
});

示例响应 JSON 文件(来自文档):

{
"html_attributions" : [],
"results" : [
{
"geometry" : {
"location" : {
"lat" : -33.870775,
"lng" : 151.199025
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/travel_agent-71.png",
"id" : "21a0b251c9b8392186142c798263e289fe45b4aa",
"name" : "Rhythmboat Cruises",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 270,
"html_attributions" : [],
"photo_reference" : "CnRnAAAAF-LjFR1ZV93eawe1cU_3QNMCNmaGkowY7CnOf-kcNmPhNnPEG9W979jOuJJ1sGr75rhD5hqKzjD8vbMbSsRnq_Ni3ZIGfY6hKWmsOf3qHKJInkm4h55lzvLAXJVc-Rr4kI9O1tmIblblUpg2oqoq8RIQRMQJhFsTr5s9haxQ07EQHxoUO0ICubVFGYfJiMUPor1GnIWb5i8",
"width" : 519
}
],
"place_id" : "ChIJyWEHuEmuEmsRm9hTkapTCrk",
"scope" : "GOOGLE",
"alt_ids" : [
{
"place_id" : "D9iJyWEHuEmuEmsRm9hTkapTCrk",
"scope" : "APP"
}
],
"reference" : "CoQBdQAAAFSiijw5-cAV68xdf2O18pKIZ0seJh03u9h9wk_lEdG-cP1dWvp_QGS4SNCBMk_fB06YRsfMrNkINtPez22p5lRIlj5ty_HmcNwcl6GZXbD2RdXsVfLYlQwnZQcnu7ihkjZp_2gk1-fWXql3GQ8-1BEGwgCxG-eaSnIJIBPuIpihEhAY1WYdxPvOWsPnb2-nGb6QGhTipN0lgaLpQTnkcMeAIEvCsSa0Ww",
"types" : [ "travel_agency", "restaurant", "food", "establishment" ],
"vicinity" : "Pyrmont Bay Wharf Darling Dr, Sydney"
}
],
"status" : "OK"
}

所以我的问题是如何只打印 JSON 请求的“name”元素?

-谢谢

最佳答案

假设 results 数组仅包含 2 个元素,您可以使用 results[0] 获取第一个元素,然后使用属性的 name 获取。

加起来就是:results[0].name

为了获得结果,您可能需要从响应正文中获取它:

request(url_nearby, {json: true}, function(err, response){
if(err){
console.log(err);
}else{
console.log(response.body.results[0].name);
}
});

关于node.js - 读取 Google 响应 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53878214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com