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

无法从Google Place Search API返回的JSON中提取数据

解决Google Place Search API数据访问问题

我来帮你搞定这个问题!你遇到的data.results返回undefined的情况,大概率是因为返回的JSON结构和你预期的不一样,或者请求本身有问题,咱们一步步来排查:

1. 先搞清楚返回的JSON到底长啥样

虽然你console.log(data)能看到JSON,但有时候控制台会折叠嵌套结构,导致你没看到真实的层级。建议你换两种方式打印:

  • 用console.dir(data):能展开完整的对象结构,方便你查看所有键名;
  • 用console.log(JSON.stringify(data, null, 2)):把JSON格式化后打印,能清晰看到所有字段,比如是否是data.response.results、data.items,而不是直接的data.results。

2. 检查你的请求URL是否正确

你直接拼接keyword、location这些参数的时候,如果里面有空格或者特殊字符,会导致请求格式错误,API返回的可能是错误信息而非正常结果。解决方法是给每个参数做URL编码:

const encodedKeyword = encodeURIComponent(keyword);
const encodedLocation = encodeURIComponent(location);
const encodedCountry = encodeURIComponent(country);
let dataURI = `${URI}${encodedKeyword}+${encodedLocation}+${encodedCountry}${API}`;

另外,你可以把proxyUrl + targetUrl这个完整URL复制到浏览器地址栏直接访问,看看返回的JSON结构是否符合预期,同时检查API是否返回了error_message字段(比如API key无效、配额不足等问题)。

3. 先验证响应状态是否正常

有时候请求可能返回了400/403这类错误,但你直接调用res.json()还是会解析出一个对象,这个对象里肯定没有results字段。建议在第一个then里先检查响应状态:

.then((res) => {
  if (!res.ok) {
    throw new Error(`请求失败,状态码:${res.status}`);
  }
  return res.json();
})

这样能及时发现请求是否成功,避免在错误的响应里找results。

4. 示例修改后的代码

结合上面的排查点,给你调整后的代码参考:

getData = (keyword, location, country) => { 
  // 对参数做URL编码,避免特殊字符导致请求错误
  const encodedKeyword = encodeURIComponent(keyword);
  const encodedLocation = encodeURIComponent(location);
  const encodedCountry = encodeURIComponent(country);
  
  let dataURI = `${URI}${encodedKeyword}+${encodedLocation}+${encodedCountry}${API}`; 
  const proxyUrl = 'https://cors-anywhere.herokuapp.com/';
  const targetUrl = dataURI;

  fetch(proxyUrl + targetUrl) 
    .then((res) => {
      // 先检查响应是否正常
      if (!res.ok) {
        throw new Error(`HTTP错误!状态码:${res.status}`);
      }
      return res.json();
    })
    .then((data) => { 
      // 打印格式化后的完整响应,方便排查结构
      console.log('完整响应数据:', JSON.stringify(data, null, 2)); 
      
      // 检查API是否返回错误信息
      if (data.error_message) {
        console.error('API错误提示:', data.error_message);
        return;
      }
      
      // 兼容可能的不同结构,根据实际情况调整键名
      const results = data.results || data.items || data.response?.results;
      console.log('获取到的结果:', results);
    }) 
    .catch((e) => {
      console.error('请求过程出错:', e);
    });
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:21:53