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

Node.js中扁平化API返回JSON并导出CSV的技术求助

亚马逊API嵌套JSON扁平化与CSV导出解决方案

问题背景

调用亚马逊API获取到嵌套结构的JSON响应,需要提取客户姓名、产品名称、SKU、评论内容、星级评分、创建时间字段并导出为CSV文件。尝试直接提取字段构建记录但无法循环迭代,使用Object.keys等方法也因嵌套结构受阻。

API返回的JSON结构示例

{
  "total_reviews": 574,
  "stars_stat": {
    "1": "2%",
    "2": "1%",
    "3": "3%",
    "4": "8%",
    "5": "85%"
  },
  "result": [
    {
      "id": "R3BWKTLO7CM3Y9",
      "asin": {},
      "review_data": "Reviewed in the United States on April 15, 2022",
      "date": {
        "date": "April 15, 2022",
        "unix": 1649988000
      },
      "name": "Sally N.",
      "rating": 5,
      "title": "Great alcohol !",
      "review": "Great products",
      "verified_purchase": true
    }
    // 其余9条评论结构类似
  ]
}

解决方案

核心思路是遍历result数组中的每条评论,将嵌套字段扁平化提取,构建符合CSV要求的记录数组,再通过csv-writer导出。

修改后的完整代码

const axios = require("axios");
const createCsvWriter = require('csv-writer').createObjectCsvWriter;

// 配置CSV写入器,定义表头与对应字段
const csvWriter = createCsvWriter({
  path: './ProductReviews.csv',
  header: [
    { id: 'customername', title: '客户姓名' },
    { id: 'productname', title: '产品名称' },
    { id: 'sku', title: 'SKU' },
    { id: 'reviewcontent', title: '评论内容' },
    { id: 'starrating', title: '星级评分' },
    { id: 'timeanddate', title: '创建时间' }
  ]
});

const options = {
  method: 'GET',
  url: 'https://amazon23.p.rapidapi.com/reviews',
  params: { asin: 'B00DUGMVC6', sort_by: 'recent', page: '1', country: 'US' },
  headers: {
    'X-RapidAPI-Key': 'redacted',
    'X-RapidAPI-Host': 'redacted'
  }
};

axios.request(options).then(function (response) {
  const reviews = response.data.result;
  // 遍历评论数组,构建CSV记录
  const csvRecords = reviews.map(review => ({
    customername: review.name,
    productname: 'Isopropyl Alcohol 99.9%', // 固定产品名,可根据需求动态获取
    sku: 'B00DUGMVC6', // 或从review.asin中提取,根据实际API返回结构调整
    reviewcontent: review.review,
    starrating: review.rating,
    timeanddate: review.date.date
  }));

  // 写入CSV文件
  csvWriter.writeRecords(csvRecords)
    .then(() => {
      console.log('CSV文件导出完成');
    })
    .catch(err => {
      console.error('写入CSV出错:', err);
    });
}).catch(function (error) {
  console.error('API请求出错:', error);
});

关键说明

  • 遍历数组:使用Array.map()遍历response.data.result,每条评论对应一条CSV记录,解决循环迭代问题。
  • 扁平化字段:直接从嵌套结构中提取需要的字段,比如review.date.date获取创建时间,review.name获取客户姓名。
  • CSV配置:明确指定表头的显示名称与对应字段ID,确保导出的CSV结构清晰。
  • 错误处理:为CSV写入和API请求添加错误捕获,便于排查问题。

可选优化

  • 如果asin字段包含产品信息,可替换固定的productname和sku,比如sku: review.asin.yourSkuField(需根据API实际返回的asin结构调整)。
  • 使用moment格式化时间:若需要统一时间格式,可引入moment处理timeanddate字段,例如timeanddate: moment(review.date.date, 'MMMM DD, YYYY').format('YYYY-MM-DD')。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:57:58