node.js - 如何将 API 获取的包含 ''' 或 '&' 或 '"' 的数据转换为它们在 nodeJs 中的人类可读值?
问题描述
在进行 API 调用时,我会返回以下值,例如:
- Niall Horan - “慢手” (索菲亚斯科特封面)
- 慢手 - Niall Horan | KINA GRANNIS & KHS 封面
- Bruno Mars - That's What I Like (from the 2017 Brit Awards) (Official Live Performance)
注意这里的 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
,decodeURIComponent
并unescape
没有帮助。请建议。
解决方案
正如@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);
推荐阅读
- php - 在 WooCommerce 中为客人和客户的字段设置邮政编码
- c# - asp.net core Razor Pages 的 Google 图表
- javascript - 在反应应用程序中调整 img 背景大小的问题
- geolocation - 地理点超出预期边界
- asp.net-core - 播种数据 - 没有 ID 的自有类型
- c# - 我的 Azure 函数的异常在 Application Insights 中记录了 3 次
- apache-kafka - kafka datadog 未正确发送指标
- c++ - C ++:如何从文件中读取多行直到某个字符,将它们存储在数组中并移动到文件的下一部分
- javascript - 当数组大于一个时pdfmake生成错误
- java - 代表用户创建谷歌日历