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

JavaScript如何访问深度嵌套对象并将API返回数据导出为CSV文件

解决方法

字段访问规则

你输出的data[key]就是包含所有数据的对象数组,访问嵌套字段的规则很简单:

  • 取时间戳:数组单个元素.timestamp
  • 取Result内的字段:数组单个元素.result.对应字段名,比如取广告伙伴名称就是.result.last_attributed_touch_data_tilde_advertising_partner_name

完整修改后代码

const url = "https://api2.branch.io/v1/query/analytics";
// 定义CSV转义函数,避免格式错乱
function escapeCsv(text) {
  if (text === null || text === undefined) return ''
  text = text.toString()
  // 内容包含逗号、双引号、换行的话用双引号包裹
  if (text.includes(',') || text.includes('"') || text.includes('\n')) {
    return `"${text.replace(/"/g, '""')}"`
  }
  return text
}

async function callApi() {
  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
        "Accept": "application/json; charset=UTF-8",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data) // 注意这里的data是你要传的请求参数,提前定义好
    })
    const resData = await response.json()
    // 取你打印的那个数据数组,如果你知道外层固定key可以直接用resData.xxx替换
    const dataArray = Object.values(resData)[0]
    // 定义CSV表头,和你要提取的字段对应
    const headers = ['时间戳', '活动名称', '广告合作伙伴', '活动ID', '唯一计数']
    // 定义要提取的result内的字段名,顺序和表头对应
    const resultFields = [
      'last_attributed_touch_data_tilde_campaign',
      'last_attributed_touch_data_tilde_advertising_partner_name',
      'last_attributed_touch_data_tilde_campaign_id',
      'unique_count'
    ]
    // 拼CSV内容,先加表头
    let csvContent = headers.map(escapeCsv).join(',') + '\n'
    // 遍历所有数据条目
    dataArray.forEach(item => {
      const row = [
        item.timestamp,
        ...resultFields.map(field => item.result[field])
      ]
      csvContent += row.map(escapeCsv).join(',') + '\n'
    })
    // 生成CSV文件并触发浏览器下载
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const downloadUrl = URL.createObjectURL(blob)
    const downloadLink = document.createElement('a')
    downloadLink.href = downloadUrl
    downloadLink.setAttribute('download', '广告数据统计.csv')
    document.body.appendChild(downloadLink)
    downloadLink.click()
    document.body.removeChild(downloadLink)
  } catch (error) {
    console.log('请求出错', error)
  }
}

callApi()

注意事项

  • 如果你接口返回的外层data的key是固定值,你可以直接用resData.你的key代替Object.values(resData)[0],性能更好
  • 表头和提取的resultFields可以根据你实际需要的字段自行增减,只要保证两者顺序对应即可
  • 如果你是在Node.js环境运行,不需要触发浏览器下载,直接用fs模块把csvContent写入本地文件即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 02:15:08