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

如何在JS中从YouTube API响应提取videoId字段

How to Extract videoId from YouTube API Response in Node.js

Hey there, I see you're trying to grab the latest video ID from Camodo Gaming's YouTube channel using the request module, but struggling with extracting the videoId from the JSON response—using split here isn't the right approach, since JSON is structured data meant to be parsed into a JavaScript object instead of hacked apart with string methods.

Let me walk you through the correct solution:

Corrected Code Example

var request = require('request');
request('https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCC6ulNJ-KDoIa3VI2gcvQpA&maxResults=1&order=date&type=video&key={token}', function (error, response, body) {
  // Handle request errors first
  if (error) {
    console.error('Request error:', error);
    return;
  }

  // Verify the API request was successful
  if (response && response.statusCode !== 200) {
    console.error('API request failed with status:', response.statusCode);
    return;
  }

  // Parse the raw JSON string into a usable JavaScript object
  var data = JSON.parse(body);

  // Extract the videoId safely
  if (data.items && data.items.length > 0) {
    var videoId = data.items[0].id.videoId;
    console.log('Latest video ID:', videoId);
  } else {
    console.log('No videos found for the channel');
  }
});

Key Details to Note:

  • Parse the JSON Response: JSON.parse(body) converts the raw API response string into a nested object, which lets you access properties directly instead of fumbling with string splits.
  • Navigate the Response Structure: The YouTube Search API returns results in the items array. Since we set maxResults=1, we target the first item (items[0]). The videoId is nested inside the id object of each video entry.
  • Added Robustness: I included checks for request errors and non-success status codes to help you catch issues like invalid API keys or rate limits before trying to parse the response.

Don't forget to replace {token} with your actual YouTube Data API key!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:45:09