You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase函数调用Google Places API:如何解析响应为JSON对象?

解决Google Places API响应无法解析的问题

嘿,我一眼就看出问题出在哪了——你用request库发起请求后,拿到的response其实是原始的JSON字符串,不是已经解析好的JavaScript对象!所以你直接去访问response.result肯定会得到undefined,自然拿不到营业时间数据。

问题根源

默认情况下,request库不会自动把API返回的JSON字符串解析成对象,你之前尝试的response.result.opening_hours.json()是错误用法——这里的response不是浏览器环境里的Response对象,根本没有.json()方法。

两种解决方案

方案1:让request自动解析JSON(推荐)

在你的optionsAPI配置里加上json: true,这样request会自动把响应解析成JavaScript对象,你就能直接访问response.result了:

export const mapGooglePlaces = functions.database
 .ref('/shopping-carts/{shoppingCartId}/shippingManner')
 .onWrite(event => {
 const shippingManner = event.data.val();
 const optionsAPI = {
 method: 'GET',
 uri: 'https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=YOUR_API_KEY',
 json: true, // 开启自动JSON解析
 };
 return request(optionsAPI)
 .then(response => {
 const openingHours = response.result.opening_hours;
 console.log(openingHours); // 现在能正常拿到营业时间数据了
 return;
 })
 .catch(function (err) {
 console.log(err);
 });
 });

方案2:手动解析JSON字符串

如果不想修改请求配置,也可以在拿到response后手动用JSON.parse()解析字符串:

export const mapGooglePlaces = functions.database
 .ref('/shopping-carts/{shoppingCartId}/shippingManner')
 .onWrite(event => {
 const shippingManner = event.data.val();
 const optionsAPI = {
 method: 'GET',
 uri: 'https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=YOUR_API_KEY',
 };
 return request(optionsAPI)
 .then(response => {
 const parsedResponse = JSON.parse(response); // 手动解析为对象
 const openingHours = parsedResponse.result.opening_hours;
 console.log(openingHours);
 return;
 })
 .catch(function (err) {
 console.log(err);
 });
 });

额外提醒

记得把代码里的YOUR_API_KEY替换成你自己的Google Places API密钥,不然请求会因权限问题失败哦。

内容的提问来源于stack exchange,提问作者Joris Cornelis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:07:32