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

NodeJS中如何遍历API响应并访问对象内部字段?

问题

我在AWS Lambda中编写了一段NodeJS代码(作为Lambda整体的一部分),用于调用外部API获取赛事日程数据,已成功获取API响应,但不清楚如何访问JSON响应中所需的内部字段。这是我首次使用JS和NodeJS,对此并不熟悉。

代码示例:

const promise = new Promise((resolve, reject) => {
  
  const options = {
  host: 'MY_HOST',
  path: 'MY_PATH',
   headers: {
        'key': 'value'
      }
    }
  
    const req = https.get(options, res => {
      let rawData = '';

      res.on('data', chunk => {
        rawData += chunk;
      });

      res.on('end', () => {
        try {
          resolve(JSON.parse(rawData));
        } catch (err) {
          reject(new Error(err));
        }
      });
    });
    
    req.on('error', err => {
      reject(new Error(err));
    });
  });
  
  // TODO - get promise result and iterate response
  promise.then();

API返回的响应示例(仅展示首个对象):

{
  "_id": {
    "$oid": "6346b02601a3c2111621c8e4"
  },
  "orgId": "1",
  "year": "2023",
  "schedule": [
    {
      "tournId": "464",
      "name": "Fortinet Championship",
      "timeZone": "America/Los_Angeles",
      "date": {
        "weekNumber": "37",
        "start": {
          "$date": {
            "$numberLong": "1663200000000"
          }
        },
        "end": {
          "$date": {
            "$numberLong": "1663459200000"
          }
        }
      },
      "format": "stroke",
      "courses": [
        {
          "host": "Yes",
          "location": {
            "state": "CA",
            "city": "Napa",
            "country": "USA"
          },
          "courseName": "Silverado Resort and Spa (North Course)",
          "courseId": "552"
        }
      ],
      "purse": {
        "$numberInt": "8000000"
      },
      "winnersShare": {
        "$numberInt": "1440000"
      },
      "fedexCupPoints": {
        "$numberInt": "500"
      }
    }
  ]
}

我需要访问的字段为:

schedule[0].date.start
schedule[0].date.end

目的是实现如下逻辑:

// loop each result and assert if current epoch is in the date Range
var currentTournamentId;
  
for(){
    if(currentEpoch >= schedule.date.start && currentEpoch <=  schedule.date.end) {
        currentTournamentId = currentTournament.getId();
        break;
    }
}

请问该如何从API响应中访问这些字段?

解决方案

1. 接收Promise返回的响应数据

在promise.then()中传入回调函数,参数就是解析后的JSON对象,同时添加错误捕获处理:

promise.then((responseData) => {
  // 在这里处理响应数据
}).catch((err) => {
  // 处理请求或JSON解析错误
  console.error('请求失败:', err);
});

2. 访问目标字段

注意API返回的日期字段嵌套结构是date.start.$date.$numberLong,需要逐层访问,并且要把字符串类型的时间戳转为数字:

  • 单场赛事开始时间:parseInt(responseData.schedule[0].date.start.$date.$numberLong, 10)
  • 单场赛事结束时间:parseInt(responseData.schedule[0].date.end.$date.$numberLong, 10)

3. 实现遍历判断逻辑

遍历schedule数组,逐个检查当前时间是否在赛事的日期范围内,找到匹配的赛事ID:

promise.then((responseData) => {
  // 获取当前时间的毫秒级时间戳
  const currentEpoch = Date.now();
  let currentTournamentId;

  // 遍历所有赛事
  for (const tournament of responseData.schedule) {
    // 解析时间戳为数字
    const startTimestamp = parseInt(tournament.date.start.$date.$numberLong, 10);
    const endTimestamp = parseInt(tournament.date.end.$date.$numberLong, 10);

    // 判断当前时间是否在赛事周期内
    if (currentEpoch >= startTimestamp && currentEpoch <= endTimestamp) {
      currentTournamentId = tournament.tournId;
      break; // 找到匹配项后退出循环
    }
  }

  // 输出或使用找到的赛事ID
  console.log('当前赛事ID:', currentTournamentId);
  // 可在此添加后续业务逻辑,比如返回结果到Lambda调用方
}).catch((err) => {
  console.error('获取日程数据失败:', err);
});

完整代码替换

将原代码中的promise.then()部分替换为上述逻辑,完整的Lambda代码片段如下:

const https = require('https'); // 确保引入https模块

const promise = new Promise((resolve, reject) => {
  const options = {
    host: 'MY_HOST',
    path: 'MY_PATH',
    headers: {
      'key': 'value'
    }
  };

  const req = https.get(options, res => {
    let rawData = '';

    res.on('data', chunk => {
      rawData += chunk;
    });

    res.on('end', () => {
      try {
        resolve(JSON.parse(rawData));
      } catch (err) {
        reject(new Error(err));
      }
    });
  });

  req.on('error', err => {
    reject(new Error(err));
  });
});

// 处理Promise结果
promise.then((responseData) => {
  const currentEpoch = Date.now();
  let currentTournamentId;

  for (const tournament of responseData.schedule) {
    const startTimestamp = parseInt(tournament.date.start.$date.$numberLong, 10);
    const endTimestamp = parseInt(tournament.date.end.$date.$numberLong, 10);

    if (currentEpoch >= startTimestamp && currentEpoch <= endTimestamp) {
      currentTournamentId = tournament.tournId;
      break;
    }
  }

  console.log('当前赛事ID:', currentTournamentId);
}).catch((err) => {
  console.error('获取日程数据失败:', err);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:51:41