首页 > 解决方案 > 如何将 API 获取的包含 ''' 或 '&' 或 '"' 的数据转换为它们在 nodeJs 中的人类可读值?

问题描述

在进行 API 调用时,我会返回以下值,例如:

注意这里的 ASCII 代码,或者我假设。

如何将这些字符串转换为人类可读的字符串?

这就是我进行 API 调用的方式:

async function ytAxiosGetFunc(queryOfYtAxiosGetFunc, maxResultsOfYtAxiosGetFunc) {

  let ytExtractedResult = [];
  let ytVideoId = [];
  let ytVideoThumb = [];
  let ytVideoTitle = [];
  let ytVideoChannel = [];
  urlOfYtAxiosGetFunc = "https://www.googleapis.com/youtube/v3/search?key=" + keys.google.apiKey[1] + "&part=snippet&order=relevance&type=video&videoEmbeddable=true";

  try {
    let ytResponse = await axios({
      url: urlOfYtAxiosGetFunc,
      method: "get",
      params: {
        q: queryOfYtAxiosGetFunc,
        maxResults: maxResultsOfYtAxiosGetFunc
      }
    })

    let ytResult = ytResponse.data;

    for (i = 0; i < (ytResult.items).length; i++) {
      ytVideoId[i] = ytResult.items[i].id.videoId;
      ytVideoThumb[i] = ytResult.items[i].snippet.thumbnails.default.url;
      ytVideoTitle[i] = unescape(ytResult.items[i].snippet.title);
      ytVideoChannel[i] = decodeURI(ytResult.items[i].snippet.channelTitle);
    }

    return {
      id: ytVideoId,
      thumb: ytVideoThumb,
      title: ytVideoTitle,
      channel: ytVideoChannel
    };
  } catch (e) {
    console.log(e);
  }
}

使用decodeURI,decodeURIComponentunescape没有帮助。请建议。

标签: node.jsexpressaxiosyoutube-data-api

解决方案


正如@stvar所建议的那样。

https://stackoverflow.com/a/66354130/14597561回答了这个问题。

它对我有用,如下所示:

npm install he
const he = require("he");
ytVideoTitle[i] = he.decode(ytResult.items[i].snippet.title);
ytVideoChannel[i] = he.decode(ytResult.items[i].snippet.channelTitle);

推荐阅读