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

如何访问API返回的JSON对象并获取其中数据?

Fixing Your API Data Access Issue

Hey there, let's break down why your code isn't working as expected and get it sorted out step by step:

1. The Return Statement Blocking Your Second Log

In your success callback, you’ve got two return console.log(...) lines. The first return immediately exits the function, so the second log (trying to access data[0].id) never runs at all. You don’t need return with console.log—just remove those keywords, and both logs will execute.

2. Mismatched JSON Structure Access

Looking at your JSON screenshot, the top-level response is an object that contains a data property (which is the array you want to work with). Your current code tries data[0].id, which treats the entire response as an array—but it’s not. You need to first access the data array inside the response object.

Corrected Code

Here’s the fixed version of your AJAX call:

$(function() {
  $.ajax({
    type: 'GET',
    url: "xxx",
    dataType: 'json',
    success: function(response) {
      console.log('success', response);
      // Access the nested data array first, then get the first item's id
      console.log(response.data[0].id);
    },
    beforeSend: function(xhr, settings) {
      xhr.setRequestHeader('Authorization', 'Bearer ' + 'xxx');
    }
  });
});

Extra Debugging Tips

  • Use console.dir(response) instead of console.log if you want to explore the full structure of the response object interactively in your browser’s dev tools.
  • To avoid errors if the data array is empty or missing, add a quick check:
    if (response.data && response.data.length > 0) {
      console.log(response.data[0].id);
    } else {
      console.log('No data found in the response');
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:24:08