【问题标题】:YouTube PlaylistItems API causing syntax errors when using JSON.parse()YouTube PlaylistItems API 在使用 JSON.parse() 时导致语法错误
【发布时间】:2020-08-17 07:57:34
【问题描述】:

我的 NodeJS 代码中有 2 个对 YouTube v3 API 的调用:channelsPlaylistItems。它们都返回 JSON 并且对第一个调用的响应被解析得很好,但是解析对第二个调用的响应会导致语法错误。我不确定这是我这边的错误还是 PlaylistItems API 端点中的错误。

这是我的代码(去掉了不相关的部分):

// At start of the bot, fetches the latest video which is compared to if an announcement needs to be sent
function setLatestVideo () {
    fetchData().then((videoInfo) => {
        if (videoInfo.error) return;

        latestVideo = videoInfo.items[0].snippet.resourceId.videoId;
    });
}

// Fetches data required to check if there is a new video release
async function fetchData () {
    let path = `channels?part=contentDetails&id=${config.youtube.channel}&key=${config.youtube.APIkey}`;
    const channelContent = await callAPI(path);

    path = `playlistItems?part=snippet&maxResults=1&playlistId=${channelContent.items[0].contentDetails.relatedPlaylists.uploads}&key=${config.youtube.APIkey}`;
    const videoInfo = await callAPI(path);

    return videoInfo;
}

// Template HTTPS get function that interacts with the YouTube API, wrapped in a Promise
function callAPI (path) {
    return new Promise((resolve) => {

        const options = {
            host: 'www.googleapis.com',
            path: `/youtube/v3/${path}`
        };

        https.get(options, (res) => {
            if (res.statusCode !== 200) return;

            const rawData = [];
            res.on('data', (chunk) => rawData.push(chunk));
            res.on('end', () => {
                try {
                    resolve(JSON.parse(rawData));
                } catch (error) { console.error(`An error occurred parsing the YouTube API response to JSON, ${error}`); }
            });

        }).on('error', (error) => console.error(`Error occurred while polling YouTube API, ${error}`));
    });
}

我遇到的错误示例:Unexpected token , in JSONUnexpected number in JSON

直到大约 2 周前,这段代码可以正常工作而不会引发任何错误,我不知道发生了什么变化,而且似乎无法弄清楚。这可能是什么原因造成的?

【问题讨论】:

    标签: node.js json youtube-api


    【解决方案1】:

    10 分钟后,我找到了解决办法!变量rawData 包含一个Buffer 并进一步研究,我认为我应该在rawData 上使用Buffer.concat(),然后再调用JSON.parse()。事实证明,这正是我们所需要的。

    在编写此代码仅 6 个月后,我仍然不确定这是如何导致问题的,但这种情况往往会发生。

    更改代码:

    res.on('end', () => {
                    try {
                        resolve(JSON.parse(Buffer.concat(rawData)));
                    } catch (error) { console.error(`An error occurred parsing the YouTube API response to JSON, ${error}`); }
                });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      • 2019-01-28
      相关资源
      最近更新 更多