首页 > 解决方案 > YouTube PlaylistItems API 在使用 JSON.parse() 时导致语法错误

问题描述

我在我的 NodeJS 代码中有 2 次对 YouTube v3 API 的调用:频道PlaylistItems。它们都返回 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.jsjsonyoutube-api

解决方案


10分钟后,我找到了解决办法!该变量rawData包含 aBuffer并且对其进行了更多研究,我认为我应该在调用它之前使用Buffer.concat()on 。事实证明,这正是所需要的。rawDataJSON.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}`); }
            });

推荐阅读