我想使用以下调用从YouTube获取自动建议:
await fetch('https://suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=skrillex&callback=suggestCallback')
.then(response => console.log(response))
此调用将获得以下JSON结果:
"suggestCallback && suggestCallback(["skrillex",[["skrillex",0],["skrillex bangarang",0],["skrillex make it bun dem",0],["skrillex scary monsters and nice sprites",0],["skrillex cinema",0],["skrillex live",0],["skrillex first of the year",0],["skrillex sicko mode",0],["skrillex kyoto",0],["skrillex remix",0]],{"k":1,"q":"bEJKh2TVzWqSICI3U3xEdXTC00g"}])"
但是,我正在努力将该结果转换为一系列“实际建议”。例如,我想以以下格式存储上面获得的JSON:
let myArray = ["skrillex", "skrillex bangarang", "skrillex make it bun dem", "skrillex scary monsters and nice sprites", "skrillex cinema", "skrillex live", "skrillex first of the year", "skrillex sicko mode", "skrillex kyoto" ,"skrillex remix"]
要实现这一目标,什么是可行的解决方案?
答案 0 :(得分:1)
执行此操作的一种方法是使用正则表达式从收到的响应中过滤出json响应,然后根据该结果创建一个数组。
let jsonp = 'suggestCallback && suggestCallback(["skrillex",[["skrillex",0],["skrillex bangarang",0],["skrillex make it bun dem",0],["skrillex scary monsters and nice sprites",0],["skrillex cinema",0],["skrillex live",0],["skrillex first of the year",0],["skrillex sicko mode",0],["skrillex kyoto",0],["skrillex remix",0]],{"k":1,"q":"bEJKh2TVzWqSICI3U3xEdXTC00g"}])';
let myRe = /\[(.*)\]/g;
let regExGroups = myRe.exec(jsonp);
let json = JSON.parse(regExGroups[0]);
let myArray = [];
json[1].forEach((element) => {
myArray.push(element[0]);
});
console.log('suggestions array', myArray);
https://jsfiddle.net/zeonfrost/s7b4aLr6/
但是您真正应该做的是定义一个describeCallback函数what is jsonp